Python django.template.defaultfilters.slugify() Examples

The following are 30 code examples of django.template.defaultfilters.slugify(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.template.defaultfilters , or try the search function .
Example #1
Source File: device.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def model_from_slug(product_line, model=None):
    """
    Returns product description for model slug or models dict for
    the specified product line
    """
    if not cache.get("slugmap"):
        slugmap = {}  # Map model slug to corresponding product description
        product_lines = gsxws.products.models()

        for k, v in product_lines.items():
            d = {}
            for p in v['models']:
                slug = slugify(p)
                d[slug] = p

            slugmap[k] = d

        cache.set("slugmap", slugmap)

    models = cache.get("slugmap").get(product_line)

    if model is not None:
        return models.get(model)

    return models 
Example #2
Source File: built_form.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def update_or_create_built_form_examples(self, array_of_examples):

        built_form_key = self.key

        self.examples.clear()

        for object in array_of_examples:

            name = object["study_area_name"]
            name_slug = slugify(name).replace('-','_')
            study_area_aerial_map_view = object["study_area_aerial_map_view"]
            study_area_street_view = object["study_area_street_view"]
            example = BuiltFormExample.objects.update_or_create(
                key="%s_%s" % (built_form_key, name_slug),
                defaults=dict(
                    url_aerial = study_area_aerial_map_view,
                    url_street = study_area_street_view,
                    name=name
                ))[0]
            self.examples.add(example) 
Example #3
Source File: models.py    From arguman.org with GNU Affero General Public License v3.0 6 votes vote down vote up
def save(self, *args, **kwargs):
        """
        - Make unique slug if it is not given.
        """
        if not self.slug:
            slug = slugify(unidecode(self.title))
            duplications = Contention.objects.filter(slug=slug)
            if duplications.exists():
                self.slug = "%s-%s" % (slug, uuid4().hex)
            else:
                self.slug = slug

        if not kwargs.pop('skip_date_update', False):
            self.date_modification = datetime.now()

        return super(Contention, self).save(*args, **kwargs) 
Example #4
Source File: views.py    From django-simple-forum with MIT License 6 votes vote down vote up
def form_valid(self, form):
        topic = self.get_object()
        old_tags = [tag.title for tag in topic.tags.all()]
        topic = form.save()
        tags_text = form.cleaned_data['tags']
        if tags_text:
            new_tags = tags_text.split(',')
            remove_tags = set(new_tags) - set(old_tags)
            for tag in new_tags:
                tag_slug = slugify(tag)
                if not Tags.objects.filter(slug=tag_slug).exists():
                    tag = Tags.objects.create(slug=tag_slug, title=tag)
                    topic.tags.add(tag)
                else:
                    tag = Tags.objects.filter(slug=tag_slug).first()
                    if tag.title in remove_tags:
                        topic.remove(tag)
                    else:
                        topic.tags.add(tag)
        topic.save()
        return JsonResponse({"error": False, "success_url": reverse('django_simple_forum:signup')}) 
Example #5
Source File: models.py    From open-context-py with GNU General Public License v3.0 6 votes vote down vote up
def make_manifest_slug(self, uuid, label, item_type, project_uuid):
        """
        gets the most recently updated Subject date
        """
        label = label.replace('_', ' ')
        raw_slug = slugify(unidecode(label[:55]))
        act_proj_short_id = self.get_project_index(project_uuid)
        if(raw_slug == '-' or len(raw_slug) < 1):
            raw_slug = 'x'  # slugs are not a dash or are empty
        if(act_proj_short_id is not False):
            raw_slug = str(act_proj_short_id) + '-' + raw_slug
        if(raw_slug[-1:] == '-'):
            raw_slug = raw_slug + 'x'  # slugs don't end with dashes
        raw_slug = re.sub(r'([-]){2,}', r'-', raw_slug)  # slugs can't have more than 1 dash characters
        slug = self.raw_to_final_slug(uuid, raw_slug)  # function for making sure unique slugs
        return slug 
Example #6
Source File: forms.py    From django-simple-forum with MIT License 6 votes vote down vote up
def save(self, commit=True):
        instance = super(CategoryForm, self).save(commit=False)
        instance.created_by = self.user
        instance.title = self.cleaned_data['title']
        if str(self.cleaned_data['is_votable']) == 'True':
            instance.is_votable = True
        else:
            instance.is_votable = False
        if str(self.cleaned_data['is_active']) == 'True':
            instance.is_active = True
        else:
            instance.is_active = False
        if not self.instance.id:
            instance.slug = slugify(self.cleaned_data['title'])

        if commit:
            instance.save()
        return instance 
Example #7
Source File: geojson.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def make_source_id(self, act_dir, filename):
        """ makes a source_id by sluggifying the act_dir and filename """
        dir_file = act_dir + ' ' + filename
        dir_file = dir_file.replace('_', ' ')
        self.label = dir_file
        dir_file = dir_file.replace('.', '-')
        raw_slug = slugify(unidecode(dir_file[:40]))
        if raw_slug[0] == '-':
            raw_slug = raw_slug[1:]  # slugs don't end with dashes
        if raw_slug[-1:] == '-':
            raw_slug = raw_slug[:-1]  # slugs don't end with dashes
        raw_slug = re.sub(r'([-]){2,}', r'-', raw_slug)  # slugs can't have more than 1 dash characters
        self.source_id = 'geojson:' + raw_slug
        return self.source_id 
Example #8
Source File: built_form_importer.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def construct_placetype_components(self, client):
        """
        :return: A dict keyed by BuildingType name and valued by BuildingType objects (UrbanFootprint v0.1 Built Form
        default set)
        """
        placetype_components = {}
        buildingtype_imports = self.load_buildingtype_csv(client)
        for b in buildingtype_imports:
            placetype_components[b.name] = dict(
                type='building_type',
                key='bt__' + slugify(b.name).replace('-', '_'),
                name=b.name,
                color=b.color if b.color else '#B0B0B0',
                component_category=b.category
            )

        for croptype, attributes in self.load_croptypes(client).items():
            placetype_components[croptype] = dict(
                type='crop_type',
                key='ct__' + slugify(croptype).replace('-', '_'),
                name=croptype,
                component_category=Keys.BUILDINGTYPE_AGRICULTURAL
            )


        return placetype_components 
Example #9
Source File: query_parsing.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def resolve_annotation(manager, annotation):
    class_name = annotation.lower().capitalize()
    if hasattr(sys.modules['django.db.models'], class_name):
        return getattr(sys.modules['django.db.models'], class_name)
    function_name = slugify(annotation.lower())
    if hasattr(manager, function_name):
        return function_name 
Example #10
Source File: test_models.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_model_apply_update_equipment(self):
        model_id = '_test/mymodel'
        equipment_id = '_test/myequipment'
        self._login()

        # create tags
        tag_create_url = reverse('core:tag_create')
        tag1 = {'tag': '_test/mytag1', 'description': 'this is a test tag', 'kind': 'Marker'}
        tag2 = {'tag': '_test/mytag2', 'description': 'this is a test tag', 'kind': 'Marker'}
        self.client.post(tag_create_url, tag1)
        self.client.post(tag_create_url, tag2)

        # create model
        model_data = {'entity_id': model_id, 'description': 'This is a test model'}
        model_create_url = reverse('core:model_create')
        self.client.post(model_create_url, model_data)
        # update created model's tags
        model_update_url = reverse('core:entity_tag', kwargs={'entity_id': slugify(model_id)})
        self.client.post(model_update_url, {'tag': '_test/mytag1'})
        self.client.post(model_update_url, {'tag': '_test/mytag2'})

        # create equipment without model
        eq_data = {'entity_id': equipment_id, 'description': 'This is a test equipment', 'equipment_type': 'GENERIC'}
        eq_create_url = reverse('core:equipment_create', kwargs={'site': '@A'})
        self.client.post(eq_create_url, eq_data)
        # update created equipment's model
        eq_update_url = reverse('core:entity_tag', kwargs={'entity_id': slugify(equipment_id)})
        eq_update_data = {
            'update': 1,
            'tag': 'modelRef',
            'value': model_id
        }
        self.client.post(eq_update_url, eq_update_data)

        # check model's tags applied to equipment's tags
        equipment = Entity.objects.get(entity_id=slugify(equipment_id))
        self.assertIn('_test/mytag1', equipment.m_tags)
        self.assertIn('_test/mytag2', equipment.m_tags) 
Example #11
Source File: models.py    From django-blog-it with MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        tempslug = slugify(self.name)
        if self.id:
            tag = Tags.objects.get(pk=self.id)
            if tag.name != self.name:
                self.slug = create_tag_slug(tempslug)
        else:
            self.slug = create_tag_slug(tempslug)
        super(Tags, self).save(*args, **kwargs) 
Example #12
Source File: test_models.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_create(self):
        model_id = '_test/mymodel'
        entity_id = slugify(model_id)
        note_content = 'test model note'
        create_url = reverse('core:model_create')
        view_url = reverse('core:model_detail', kwargs={"entity_id": entity_id})
        note_url = reverse('core:entity_note', kwargs={"entity_id": entity_id})
        self._login()

        data = {'entity_id': model_id, 'description': 'this is a test 2000 model'}
        response = self.client.post(create_url, data)
        self.assertRedirects(response, view_url)
        response = self.client.get(view_url, data)
        self.assertContains(response, 'this is a test 2000 model')

        data = {}
        response = self.client.post(create_url, data)
        self.assertFormError(response, 'form', 'entity_id', 'This field is required.')

        data = {'entity_id': model_id, 'description': 'another model ?'}
        response = self.client.post(create_url, data)
        self.assertFormError(response, 'form', 'entity_id', 'Model with this Model ID already exists.')

        data = {'entity_id': entity_id, 'content': note_content}
        response = self.client.post(note_url, data)
        self.assertEquals(response.status_code, 200)
        body = json.loads(response.content)
        self.assertEquals(body['success'], 1)
        note = EntityNote.objects.filter(entity_id=entity_id).first()
        self.assertIsNotNone(note)
        self.assertEquals(note.content, note_content) 
Example #13
Source File: test_models.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_delete_requires_login(self):
        model_id = '_test/mymodel'
        entity_id = slugify(model_id)
        delete_url = reverse('core:model_delete', kwargs={"entity_id": entity_id})
        data = {'entity_id': model_id, 'description': 'this is a test model'}
        response = self.client.post(delete_url, data)
        self.assertEquals(response.status_code, 302) 
Example #14
Source File: test_models.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_model_apply_create_equipment(self):
        model_id = '_test/mymodel'
        equipment_id = '_test/myequipment'
        self._login()

        # create tags
        tag_create_url = reverse('core:tag_create')
        tag1 = {'tag': '_test/mytag1', 'description': 'this is a test tag', 'kind': 'Marker'}
        tag2 = {'tag': '_test/mytag2', 'description': 'this is a test tag', 'kind': 'Marker'}
        self.client.post(tag_create_url, tag1)
        self.client.post(tag_create_url, tag2)

        # create model
        model_data = {'entity_id': model_id, 'description': 'This is a test model'}
        model_create_url = reverse('core:model_create')
        self.client.post(model_create_url, model_data)
        # update created model's tags
        model_update_url = reverse('core:entity_tag', kwargs={'entity_id': slugify(model_id)})
        self.client.post(model_update_url, {'tag': '_test/mytag1'})
        self.client.post(model_update_url, {'tag': '_test/mytag2'})

        # create equipment with created model
        eq_data = {'entity_id': equipment_id, 'description': 'This is a test equipment',
                   'model': model_id, 'equipment_type': 'GENERIC'}
        eq_create_url = reverse('core:equipment_create', kwargs={'site': '@A'})
        self.client.post(eq_create_url, eq_data)

        # check model's tags applied to equipment's tags
        equipment = Entity.objects.get(entity_id=slugify(equipment_id))
        self.assertIn('_test/mytag1', equipment.m_tags)
        self.assertIn('_test/mytag2', equipment.m_tags) 
Example #15
Source File: site.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def save(self, commit=True):
        description = self.cleaned_data['description']
        entity_id = self.cleaned_data['entity_id']
        if not entity_id or entity_id == '':
            entity_id = utils.make_random_id(description)

        object_id = entity_id
        entity_id = slugify(entity_id)
        self.cleaned_data['entity_id'] = entity_id

        site = Entity(entity_id=entity_id)
        site.add_tag('site', commit=False)
        site.add_tag('id', object_id, commit=False)
        site.add_tag('dis', description, commit=False)
        area = self.cleaned_data['area']
        if area:
            site.add_tag('area', area, commit=False)
        address = self.cleaned_data['address']
        if address:
            site.add_tag('geoAddr', address, commit=False)
        country = self.cleaned_data['country']
        if country:
            site.add_tag('geoCountry', country, commit=False)
        state = self.cleaned_data['state']
        if state:
            site.add_tag('geoState', state, commit=False)
        city = self.cleaned_data['city']
        if city:
            site.add_tag('geoCity', city, commit=False)
        timezone = self.cleaned_data['timezone']
        if timezone:
            site.add_tag('tz', timezone, commit=False)

        site.save()
        self.instance = Entity.objects.get(entity_id=entity_id)
        self._post_clean()  # reset the form as updating the just created instance
        return self.instance 
Example #16
Source File: import_data.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def import_json(source_file_name):
    reader = None
    with open(source_file_name) as f:
        reader = json.loads(f.read())

    counter_insert = 0
    counter_update = 0
    with connections['default'].cursor() as c:
        for row in reader['entities']:
            entity_id = slugify(row['entity_id'])
            topic = row.get('topic')
            kv_tags = row.get('kv_tags', {})
            m_tags = row.get('m_tags', [])

            try:
                c.execute("""INSERT INTO core_entity (entity_id, topic, kv_tags, m_tags, dashboard_uid)
                    VALUES (%s, %s, %s, %s, %s)""", [entity_id, topic, kv_tags, m_tags, ''])
                counter_insert += 1
                print('-- INSERT entity: ', entity_id)
            except IntegrityError:
                c.execute("""UPDATE core_entity SET topic = %s, kv_tags = %s, m_tags = %s
                    WHERE entity_id = %s""", [topic, kv_tags, m_tags, entity_id])
                counter_update += 1
                print('-- UPDATE entity: ', entity_id)

    print('{0} rows have been successfully processed {1} '
          'inserted {2} updated.'.format(counter_insert+counter_update, counter_insert, counter_update)) 
Example #17
Source File: reference.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def make_cache_key(self, prefix, identifier):
        """ makes a valid OK cache key """
        concat_string = str(prefix) + "-" + str(identifier)
        return slugify(unidecode(concat_string)) 
Example #18
Source File: forms.py    From django-blog-it with MIT License 5 votes vote down vote up
def clean_name(self):
        if not self.instance.id:
            if Category.objects.filter(slug=slugify(self.cleaned_data['name'])).exists():
                raise forms.ValidationError('Category with this Name already exists.')
        else:
            if Category.objects.filter(name__icontains=self.cleaned_data['name']).exclude(id=self.instance.id):
                raise forms.ValidationError('Category with this Name already exists.')

        return self.cleaned_data['name'] 
Example #19
Source File: models.py    From django-blog-it with MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        tempslug = slugify(self.title)
        if self.id:
            blogpost = Post.objects.get(pk=self.id)
            if blogpost.title != self.title:
                self.slug = create_slug(tempslug)
        else:
            self.slug = create_slug(tempslug)
            self.email_to_admins_on_post_create()

        super(Post, self).save(*args, **kwargs) 
Example #20
Source File: db.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def get_db_entity_params(layer_name):
    """
    For DbEntity creation we need a key and name. The key is a 'slugified'
    version of the name, and name is extracted from the layer.
    """

    db_entity_name = titleize(layer_name)

    # ensure we have unique names if the layer has been uploaded before
    while DbEntity.objects.filter(name=db_entity_name).count() > 0:
        db_entity_name = increment_key(db_entity_name)

    db_entity_key = slugify(db_entity_name).replace('-', '_')

    return db_entity_key, db_entity_name 
Example #21
Source File: models.py    From django-blog-it with MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs) 
Example #22
Source File: models.py    From django-blog-it with MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Theme, self).save(*args, **kwargs) 
Example #23
Source File: models.py    From Django-blog with MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        self.slug = slugify(unidecode(self.name))
        super().save(*args, **kwargs) 
Example #24
Source File: extras.py    From clist with Apache License 2.0 5 votes vote down vote up
def slug(value):
    return slugify(unidecode(value)) 
Example #25
Source File: rest.py    From scale with Apache License 2.0 5 votes vote down vote up
def title_to_basename(title):
    """Generates an identifying basename for a model from a human readable title

    :param title: The title to convert
    :type title: string
    :returns: The generated identifying name.
    :rtype: string
    """
    
    name = slugify(title)
    name = name.replace('_', '-')
    name = name[:30]
    basename = name
    
    return basename 
Example #26
Source File: models.py    From django-radio with GNU General Public License v3.0 5 votes vote down vote up
def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super(Programme, self).save(*args, **kwargs) 
Example #27
Source File: models.py    From django-radio with GNU General Public License v3.0 5 votes vote down vote up
def save(self, *args, **kwargs):
        if not self.pk:
            try:
                p = UserProfile.objects.get(user=self.user)
                self.pk = p.pk
            except UserProfile.DoesNotExist:
                pass
        self.slug = slugify(self.user.username)
        super(UserProfile, self).save(*args, **kwargs) 
Example #28
Source File: __init__.py    From zulip with Apache License 2.0 5 votes vote down vote up
def environment(**options: Any) -> Environment:
    env = Environment(**options)
    env.globals.update({
        'default_page_params': {
            'debug_mode': False,
            'webpack_public_path': staticfiles_storage.url(
                settings.WEBPACK_LOADER['DEFAULT']['BUNDLE_DIR_NAME'],
            ),
        },
        'static': staticfiles_storage.url,
        'url': reverse,
        'render_markdown_path': render_markdown_path,
    })

    env.install_gettext_translations(translation, True)

    env.filters['slugify'] = slugify
    env.filters['pluralize'] = pluralize
    env.filters['display_list'] = display_list
    env.filters['device_action'] = device_action
    env.filters['timesince'] = timesince

    return env 
Example #29
Source File: filter.py    From django-admin-rangefilter with MIT License 5 votes vote down vote up
def choices(self, cl):
        yield {
            # slugify converts any non-unicode characters to empty characters
            # but system_name is required, if title converts to empty string use id
            # https://github.com/silentsokolov/django-admin-rangefilter/issues/18
            'system_name': force_str(slugify(self.title) if slugify(self.title) else id(self.title)),
            'query_string': cl.get_query_string(
                {}, remove=self._get_expected_fields()
            )
        } 
Example #30
Source File: models.py    From django-aws-template with MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):

        slug = slugify(self.username)
        self.slug = slug
        count = 0
        while Account.objects.filter(slug=self.slug).exclude(pk=self.id).exists():
            self.slug = '{0}{1}'.format(slug, count)
            logger.debug('Slug conflict. Trying again with {0}'.format(self.slug))
            count += 1

        super(Account, self).save(*args, **kwargs)