def slug(self): if isinstance(self.authors, str): return slugify(self.authors) if len(self.authors) > 1: return '/'.join( slugify(author) for author in self.authors ) else: return slugify(self.authors[0])
def format_profile(self, request, obj, fieldname, *args, **kwargs): """IF user has a profile page return a link to it""" existing_profile = current_app.db.index.find_one( {'content_type': 'block', 'slug': slugify(obj.get('fullname'))} ) if existing_profile: edit_url = url_for( 'quokka.core.content.admin.blockview.edit_view', id=existing_profile['_id'] ) view_url = url_for( 'quokka.core.content.author', author=existing_profile['slug'] ) edit_link = html.a(href=edit_url, target='_blank')( html.i(class_="icon fa fa-pencil glyphicon glyphicon-pencil", style="margin-right: 5px;")(), 'Edit Profile' ) view_link = html.a(href=view_url, target='_blank')( html.i(class_="icon fa fa-globe glyphicon glyphicon-globe", style="margin-right: 5px;")(), 'View Profile' ) return html.div()( html.span()(edit_link), Markup(' '), html.span()(view_link) )
def on_model_change(self, form, model, is_created): if is_created: # each custom module should be identified by admin and format class self.add_module_metadata(model) getattr(self, 'before_save', lambda *a, **k: None)( form, model, is_created ) get_format(model).before_save(form, model, is_created) if not model.get('slug'): model['slug'] = slugify(model['title']) if not model.get('category'): # When category is hidden on form it should be '' model['category'] = '' existent = self.get_existent_record(form, model) if (is_created and existent) or ( existent and existent['_id'] != model['_id']): raise ValidationError( f'{url_for_content(model, include_ext=False)} already exists' ) now = dt.datetime.now() current_user = get_current_user() if is_created: # this defaults are also applied for cloning action # SIGNATURE model['_id'] = current_app.db.generate_id() model['date'] = now model['created_by'] = current_user model['published'] = False model['modified'] = None model['modified_by'] = None # DEFAULTS default_locale = current_app.config.get( 'BABEL_DEFAULT_LOCALE', 'en' ) model['language'] = self.base_query.get('language', default_locale) model['content_type'] = self.base_query.get( 'content_type', 'article' ) defaults_attr = f"{'create' if is_created else 'edit'}_defaults" for key, val in getattr(self, defaults_attr, {}).items(): model.setdefault(key, val) model['modified'] = now model['modified_by'] = current_user model.pop('csrf_token', None) self.slugify_search_data(model) current_app.db.push_content(model)
def url_for_content(content, include_ext=True): """Return a relative URL for content dict or Content model """ if not isinstance(content, dict): data = content.data else: data = content category_slug = ( data.get('category_slug') or slugify_category(data.get('category') or '') ) slug = data.get('slug') or slugify(data.get('title')) if category_slug: slug = f'{category_slug}/{slug}' content_type = data.get('content_type') if content_type not in (None, 'article', 'page'): slug = f'{content_type}/{slug}' if not include_ext: return slug ext = app.config.get("CONTENT_EXTENSION", "html") if data.get('published'): # return url_for('quokka.core.content.detail', slug=slug) return f'{slug}.{ext}' else: # return url_for('quokka.core.content.preview', slug=slug) return f'{slug}.preview'
def url_for_content(content, include_ext=True): """Return a relative URL for content dict or Content model """ if not isinstance(content, dict): data = content.data else: data = content category_slug = (data.get('category_slug') or slugify_category(data.get('category') or '')) slug = data.get('slug') or slugify(data.get('title')) if category_slug: slug = f'{category_slug}/{slug}' content_type = data.get('content_type') if content_type not in (None, 'article', 'page'): slug = f'{content_type}/{slug}' if not include_ext: return slug ext = app.config.get("CONTENT_EXTENSION", "html") if data.get('published'): # return url_for('quokka.core.content.detail', slug=slug) return f'{slug}.{ext}' else: # return url_for('quokka.core.content.preview', slug=slug) return f'{slug}.preview'
def generate_username(cls, name, user=None): name = name or '' username = slugify(name) filters = dict(username=username) if user: filters['id__ne'] = user.id if cls.objects.filter(**filters).count(): username = '******'.format(username, random.randint(1, 1000)) return username
def generate_username(cls, name): # username = email.lower() # for item in ['@', '.', '-', '+']: # username = username.replace(item, '_') # return username username = slugify(name) if cls.objects.filter(username=username).count(): username = "******".format(username, randint(1, 1000)) return username
def generate_username(cls, name, user=None): name = name or '' username = slugify(name) filters = {"username": username} if user: filters["id__ne"] = user.id if cls.objects.filter(**filters).count(): username = "******".format(username, randint(1, 1000)) return username
def test_should_replace_nonascii_chars_with_corresponding_ascii_chrs(self): self.assertEquals(slugify(u'áÁàÀãÃâÂäÄ'), 'aaaaaaaaaa') self.assertEquals(slugify(u'éÉèÈẽẼêÊëË'), 'eeeeeeeeee') self.assertEquals(slugify(u'íÍìÌĩĨîÎïÏ'), 'iiiiiiiiii') self.assertEquals(slugify(u'óÓòÒõÕôÔöÖ'), 'oooooooooo') self.assertEquals(slugify(u'úÚùÙũŨûÛüÜ'), 'uuuuuuuuuu') self.assertEquals(slugify(u'ćĆĉĈçÇ'), 'cccccc')
def on_model_change(self, form, model, is_created): if is_created: # each custom module should be identified by admin and format class self.add_module_metadata(model) get_format(model).before_save(form, model, is_created) if not model.get('slug'): model['slug'] = slugify(model['title']) existent = current_app.db.get('index', { 'slug': model['slug'], 'category': model['category'] }) if (is_created and existent) or (existent and existent['_id'] != model['_id']): raise ValidationError(f'{get_content_url(model)} already exists') now = dt.datetime.now() current_user = get_current_user() if is_created: # this defaults are also applied for cloning action model['date'] = now model['created_by'] = current_user model['_id'] = current_app.db.generate_id() model['language'] = current_app.config.get('BABEL_DEFAULT_LOCALE', 'en') model['published'] = False model['modified'] = None model['modified_by'] = None model['modified'] = now model['modified_by'] = current_user model.pop('csrf_token', None) current_app.db.push_content(model)
def on_model_change(self, form, model, is_created): # check if exists existent = db.index.find_one({ 'title': model['title'], 'category': model['category'] }) duplicate_error_message = u'{0} "{1}/{2}" {3}'.format( _('duplicate error:'), model['category'], model['title'], _('already exists.')) if (is_created and existent) or (existent and existent['_id'] != model['_id']): raise ValidationError(duplicate_error_message) if is_created: model['date'] = dt.datetime.now() model['slug'] = slugify(model['title']) else: model['modified'] = dt.datetime.now() get_format(model).before_save(form, model, is_created)
def test_should_accept_only_ascii_letters_and_numbers(self): slugged_text = slugify('''qwerty123456"'@#$%*()_+\|<>,.;:/?]~[`{}^ ''') self.assertEquals(slugged_text, 'qwerty123456')
def test_should_accept_other_input_encodings(self): slugged_text = slugify(u'Álvaro Justen') self.assertEquals(slugged_text, 'alvaro-justen')
def test_should_accept_unicode_text(self): self.assertEquals(slugify(u'Álvaro Justen'), 'alvaro-justen')
def test_should_ignore_unecessary_spaces(self): self.assertEquals(slugify(' alvaro justen '), 'alvaro-justen')
def validate_slug(self, title=None): if self.slug: self.slug = slugify(self.slug) else: self.slug = slugify(title or self.title)
def __init__(self, name): self.name = name self.slug = slugify(name)
def save(self, *args, **kwargs): self.identifier = slugify(self.identifier or self.title) super(SubContentPurpose, self).save(*args, **kwargs)
def test_should_accept_only_chars_in_permitted_chars_parameter(self): slugged_text = slugify('''0987654321gfdsazxcvb''', permitted_chars='abc123') self.assertEquals(slugged_text, '321acb')
def action_create_userprofile(self, ids): for _id in ids: user = current_app.db.users.find_one({'_id': _id}) if not user.get('fullname'): user['fullname'] = user['username'] current_app.db.users.update_one( {'_id': user['_id']}, {'fullname': user['fullname']} ) # This update looks like having a cache # self.coll.update_one( # {'_id': _id}, {'fullname': user['fullname']} # ) fullslug = slugify(user['fullname']) existing_block = current_app.db.get( 'index', {'content_type': 'block', 'slug': fullslug} ) if existing_block: blocklink = url_for( 'quokka.core.content.admin.blockview.edit_view', id=existing_block['_id'] ) flash(Markup( f'Profile block for {user["username"]} ' f'already exists at: ' f'<a href="{blocklink}">{existing_block["_id"]}</a>' )) else: # TODO: move creation logic to a model like obj new_data = { 'title': user['fullname'], 'slug': fullslug, 'summary': f'Profile page for {user["username"]}', 'published': True, 'comments': False, 'content_type': 'block', 'version': 0, 'date': datetime.now(), 'modified': datetime.now(), 'language': 'en', 'content_format': 'markdown', 'created_by': 'admin', 'modified_by': 'admin', 'category': '', 'category_slug': '', 'custom_vars': [ {'key': 'profile_title', 'value': f'@note change this field to customize html page title'}, # noqa {'key': 'twitter', 'value': f'@note Fill this field with user twitter profile e.g: http://twitter.com/{user["username"]}'}, # noqa {'key': 'facebook', 'value': f'@note Fill this field with user facebook profile e.g: http://facebook.com/{user["username"]}'}, # noqa {'key': 'pinterest', 'value': f'@note Fill this field with user pinterest profile e.g: http://pinterest.com/{user["username"]}'}, # noqa {'key': 'github', 'value': f'@note Fill this field with user github profile e.g http://github.com/{user["username"]}'}, # noqa {'key': 'aboutme', 'value': f'@note Fill this field with user about.me profile e.g: http://aboutme.com/{user["username"]}'}, # noqa {'key': 'instagram', 'value': f'@note Fill this field with user instagram profile e.g: http://instagram.com/{user["username"]}'}, # noqa {'key': 'site', 'value': '@note Fill this field with user website link'}, # noqa {'key': 'banner_color', 'value': '@note Fill this field with a color code or name e.g: #ffcc00 or yellow'}, # noqa {'key': 'banner_image', 'value': '@note Fill this field witha banner image url e.g: http://site.com/image.jpg'}, # noqa {'key': 'gravatar_email', 'value': '@note Fill this field with gravatar registered email e.g: [email protected]'}, # noqa {'key': 'author_avatar', 'value': '@note Fill this field with an absolute url to a profile image e.g: http://site.com/image.png'}, # noqa ], 'quokka_create_form_class': 'FormMeta', 'quokka_create_form_module': 'quokka.core.content.formats', 'quokka_format_class': 'MarkdownFormat', 'quokka_format_module': 'quokka.core.content.formats', 'quokka_module': 'quokka.core.content.admin', 'tags_slug': None, 'block_items': [], 'authors_slug': None, } new = current_app.db.insert('index', new_data) new_data['_id'] = new.inserted_id current_app.db.push_content(new_data) newlink = url_for( 'quokka.core.content.admin.blockview.edit_view', id=new.inserted_id ) flash(Markup( f'Profile block for {user["username"]} ' f'Created at: ' f'<a href="{newlink}">{new.inserted_id}</a>' ))
def test_should_always_return_lowercase_words(self): self.assertEquals(slugify('ALVAROJUSTEN'), 'alvarojusten')
def _normalize_key(self, key): return slugify(key)
def test_should_replace_space_with_dash(self): self.assertEquals(slugify('Alvaro Justen'), 'alvaro-justen')
def action_create_userprofile(self, ids): for _id in ids: user = current_app.db.users.find_one({'_id': _id}) if not user.get('fullname'): user['fullname'] = user['username'] current_app.db.users.update_one({'_id': user['_id']}, {'fullname': user['fullname']}) # This update looks like having a cache # self.coll.update_one( # {'_id': _id}, {'fullname': user['fullname']} # ) fullslug = slugify(user['fullname']) existing_block = current_app.db.get('index', { 'content_type': 'block', 'slug': fullslug }) if existing_block: blocklink = url_for( 'quokka.core.content.admin.blockview.edit_view', id=existing_block['_id']) flash( Markup( f'Profile block for {user["username"]} ' f'already exists at: ' f'<a href="{blocklink}">{existing_block["_id"]}</a>')) else: # TODO: move creation logic to a model like obj new_data = { 'title': user['fullname'], 'slug': fullslug, 'summary': f'Profile page for {user["username"]}', 'published': True, 'comments': False, 'content_type': 'block', 'version': 0, 'date': datetime.now(), 'modified': datetime.now(), 'language': 'en', 'content_format': 'markdown', 'created_by': 'admin', 'modified_by': 'admin', 'category': '', 'category_slug': '', 'custom_vars': [ { 'key': 'profile_title', 'value': f'@note change this field to customize html page title' }, # noqa { 'key': 'twitter', 'value': f'@note Fill this field with user twitter profile e.g: http://twitter.com/{user["username"]}' }, # noqa { 'key': 'facebook', 'value': f'@note Fill this field with user facebook profile e.g: http://facebook.com/{user["username"]}' }, # noqa { 'key': 'pinterest', 'value': f'@note Fill this field with user pinterest profile e.g: http://pinterest.com/{user["username"]}' }, # noqa { 'key': 'github', 'value': f'@note Fill this field with user github profile e.g http://github.com/{user["username"]}' }, # noqa { 'key': 'aboutme', 'value': f'@note Fill this field with user about.me profile e.g: http://aboutme.com/{user["username"]}' }, # noqa { 'key': 'instagram', 'value': f'@note Fill this field with user instagram profile e.g: http://instagram.com/{user["username"]}' }, # noqa { 'key': 'site', 'value': '@note Fill this field with user website link' }, # noqa { 'key': 'banner_color', 'value': '@note Fill this field with a color code or name e.g: #ffcc00 or yellow' }, # noqa { 'key': 'banner_image', 'value': '@note Fill this field witha banner image url e.g: http://site.com/image.jpg' }, # noqa { 'key': 'gravatar_email', 'value': '@note Fill this field with gravatar registered email e.g: [email protected]' }, # noqa { 'key': 'author_avatar', 'value': '@note Fill this field with an absolute url to a profile image e.g: http://site.com/image.png' }, # noqa ], 'quokka_create_form_class': 'FormMeta', 'quokka_create_form_module': 'quokka.core.content.formats', 'quokka_format_class': 'MarkdownFormat', 'quokka_format_module': 'quokka.core.content.formats', 'quokka_module': 'quokka.core.content.admin', 'tags_slug': None, 'block_items': [], 'authors_slug': None, } new = current_app.db.insert('index', new_data) new_data['_id'] = new.inserted_id current_app.db.push_content(new_data) newlink = url_for( 'quokka.core.content.admin.blockview.edit_view', id=new.inserted_id) flash( Markup(f'Profile block for {user["username"]} ' f'Created at: ' f'<a href="{newlink}">{new.inserted_id}</a>'))