Here are the examples of the python api django.utils.text.slugify taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
339 Examples
3
Source : models.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def get_next_url(self):
next_event = Event.all_visible.filter(Q(date__gt=self.date) | Q(date__exact=self.date, id__gt=self.id))\
.order_by('date', 'id').values_list("id", "name").first()
if next_event:
return reverse('view_event', args=(next_event[0], slugify(next_event[1])))
def get_prev_url(self):
3
Source : models.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def get_prev_url(self):
prev_event = Event.all_visible.filter(Q(date__lt=self.date) | Q(date__exact=self.date, id__lt=self.id))\
.order_by('-date', '-id').values_list("id", "name").first()
if prev_event:
return reverse('view_event', args=(prev_event[0], slugify(prev_event[1])))
def sources_iterator(self):
3
Source : staff_views.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def approve_source(request, source_type, pk):
if source_type == 'audio':
source = get_object_or_404(AudioSource, pk=pk)
elif source_type == 'image':
source = get_object_or_404(ImageSource, pk=pk)
else:
raise Http404
source.approve()
messages.success(request, "Source {} has been approved.".format(source.title))
logging.getLogger('palanaeum.staff').info("Source %s has been approved by %s.",
source.id, request.user)
return redirect('view_event', source.event_id, slugify(source.event.name))
@staff_member_required(login_url='auth_login')
3
Source : test_events.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def test_prev_url(self):
self.assertEqual(
self.event3.get_prev_url(),
None
)
self.assertEqual(
self.event2.get_prev_url(),
reverse('view_event', args=(self.event3.pk, slugify(self.event3.name)))
)
def test_next_url(self):
3
Source : test_events.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def test_next_url(self):
self.assertEqual(
self.event1.get_next_url(),
None
)
self.assertEqual(
self.event2.get_next_url(),
reverse('view_event', args=(self.event1.pk, slugify(self.event1.name)))
)
def test_event_view_no_slug(self):
3
Source : test_events.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def test_event_view_no_slug(self):
ret = self.client.get('/events/{}/'.format(self.event1.id), follow=True)
self.assertEqual(ret.status_code, 200)
self.assertEqual(ret.redirect_chain[0],
('/events/{}-{}/'.format(self.event1.id, slugify(self.event1.name)), 302))
def test_view_entry(self):
3
Source : test_events.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def test_view_entry(self):
entry = EntryFactory(event=self.event1)
ret = self.client.get('/entry/{}/'.format(entry.id), follow=True)
self.assertEqual(ret.status_code, 200)
self.assertEqual(
ret.redirect_chain[0],
('/events/{}-{}/#e{}'.format(self.event1.id, slugify(self.event1.name), entry.id), 302))
def test_view_event_invisible(self):
3
Source : views.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def event_no_slug(request, event_id):
"""
Redirect to a version with slug in URL.
"""
event = get_object_or_404(Event, pk=event_id)
return redirect('view_event', event_id, slugify(event.name))
def event_feed_no_slug(request, event_id):
3
Source : views.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def event_feed_no_slug(request, event_id):
"""
Redirect to a version with slug in URL.
"""
event = get_object_or_404(Event, pk=event_id)
return redirect('event_feed', event_id, slugify(event.name))
def view_entry(request, entry_id):
3
Source : views.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def view_entry(request, entry_id):
"""
Redirect user to proper event and entry.
"""
entry = get_object_or_404(Entry, pk=entry_id)
return redirect(reverse('view_event', args=(entry.event_id, slugify(entry.event.name))) + '#e{}'.format(entry.id))
def view_event(request, event_id):
3
Source : models.py
with MIT License
from acdh-oeaw
with MIT License
from acdh-oeaw
def slug_name(self):
return "{}__{}_{}".format(
slugify(self.name), self.start_date, self.end_date
)
class TempSpatial(IdProvider):
3
Source : models.py
with MIT License
from acdh-oeaw
with MIT License
from acdh-oeaw
def slug_name(self):
return "{}__{}_{}".format(
slugify(self.name), self.start_date, self.end_date
)
def sanitize_wikidataid(self):
3
Source : models.py
with MIT License
from acdh-oeaw
with MIT License
from acdh-oeaw
def save(self, *args, **kwargs):
if not self.id:
self.date_created = timezone.now()
self.date_modified = timezone.now()
if not self.identifier:
self.identifier = DEFAULT_URI + slugify(self.title, allow_unicode=True)
super(SkosConceptScheme, self).save(*args, **kwargs)
def creator_as_list(self):
3
Source : models.py
with MIT License
from acdh-oeaw
with MIT License
from acdh-oeaw
def save(self, *args, **kwargs):
if self.notation == "":
temp_notation = slugify(self.pref_label, allow_unicode=True)
concepts = len(SkosConcept.objects.filter(notation=temp_notation))
if concepts < 1:
self.notation = temp_notation
else:
self.notation = "{}-{}".format(temp_notation, concepts)
else:
pass
if not self.id:
self.date_created = timezone.now()
self.date_modified = timezone.now()
super(SkosConcept, self).save(*args, **kwargs)
def create_uri(self):
3
Source : dummy_sources.py
with Mozilla Public License 2.0
from Amsterdam
with Mozilla Public License 2.0
from Amsterdam
def handle(self, *args, **options):
to_create = int(options['to_create'] or self.default_to_create)
if not self.min_to_create < = to_create < = self.max_to_create:
self.stderr.write(f'The to create option must be an integer from {self.min_to_create} to '
f'{self.max_to_create}, {to_create} given')
else:
for _ in range(to_create):
SourceFactory.create(name=slugify(fake.words()), description=fake.sentence(nb_words=10))
self.stdout.write(f'Created {to_create} random Source(s)')
3
Source : 0011_auto_20180918_1419.py
with Mozilla Public License 2.0
from Amsterdam
with Mozilla Public License 2.0
from Amsterdam
def populate_slug_fields(apps, schema_editor):
"""Populate `slug` fields on category models."""
MainCategory = apps.get_model('signals', 'MainCategory')
SubCategory = apps.get_model('signals', 'SubCategory')
for main_category in MainCategory.objects.all():
main_category.slug = slugify(main_category.name)
main_category.save()
for sub_category in SubCategory.objects.all():
sub_category.slug = slugify(sub_category.name)
sub_category.save()
class Migration(migrations.Migration):
3
Source : preset_filters.py
with GNU General Public License v3.0
from Archmonger
with GNU General Public License v3.0
from Archmonger
def preprocess_filters(preset_filters, slug, add_values):
"""Do any preprocessing needed on the filters"""
processed_filters = {}
for key in preset_filters:
# Add any filter values needed
if add_values:
add_filter_values(add_values, preset_filters[key])
# Slugify all filter names
if slug:
processed_filters[slugify(key)] = preset_filters[key]
if processed_filters:
return processed_filters
return preset_filters
def combined_filters(filter_name=None, slug=False, add_values=()):
3
Source : entity.py
with GNU General Public License v3.0
from arrobalytics
with GNU General Public License v3.0
from arrobalytics
def generate_slug(self, force_update: bool = False):
if not force_update and self.slug:
raise ValidationError(
message=_(f'Cannot replace existing slug {self.slug}. Use force_update=True if needed.')
)
slug = slugify(self.name)
suffix = ''.join(choices(ENTITY_RANDOM_SLUG_SUFFIX, k=8))
entity_slug = f'{slug}-{suffix}'
self.slug = entity_slug
def recorded_inventory(self, user_model, queryset=None, as_values=True):
3
Source : unit.py
with GNU General Public License v3.0
from arrobalytics
with GNU General Public License v3.0
from arrobalytics
def create_entity_unit_slug(name):
slug = slugify(name)
suffix = ''.join(choices(ENTITY_UNIT_RANDOM_SLUG_SUFFIX, k=5))
unit_slug = f'{slug}-{suffix}'
return unit_slug
class EntityUnitModelManager(models.Manager):
3
Source : models.py
with GNU General Public License v3.0
from artoonie
with GNU General Public License v3.0
from artoonie
def _get_unique_slug(self):
# loop until the name is unique
slug = slugify(self.title)
if slug.endswith('json'):
slug = slug[:-4]
# at most 220 chars for slug, 20 for title, leaving 15 for numbers
slug = slug[:220]
# loop until the name is unique
num = 1
uniqueSlug = slug
while JsonConfig.objects.filter(slug=uniqueSlug).exists():
uniqueSlug = '{}-{}'.format(slug, num)
num += 1
return uniqueSlug
def __str__(self):
3
Source : gpxfile.py
with GNU General Public License v3.0
from auto-mat
with GNU General Public License v3.0
from auto-mat
def normalize_gpx_filename(instance, filename):
return "-".join(
[
"gpx_tracks/dpnk-%s/track" % instance.user_attendance.campaign.pk,
datetime.datetime.now().strftime("%Y-%m-%d"),
slugify(filename),
]
)
@with_author
3
Source : questionnaire.py
with GNU General Public License v3.0
from auto-mat
with GNU General Public License v3.0
from auto-mat
def questionnaire_filename(instance, filename):
return "questionaire/dpnk-%s/%s/%s" % (
instance.question.competition.campaign.pk,
instance.question.competition.slug,
slugify(filename),
)
class Answer(models.Model):
3
Source : trip.py
with GNU General Public License v3.0
from auto-mat
with GNU General Public License v3.0
from auto-mat
def normalize_gpx_filename(instance, filename):
return "-".join(
[
"gpx_tracks/dpnk-%s/track" % instance.user_attendance.campaign.pk,
datetime.datetime.now().strftime("%Y-%m-%d"),
slugify(filename),
]
)
def distance_all_modes(trips, campaign=None):
3
Source : models.py
with GNU Affero General Public License v3.0
from avantifellows
with GNU Affero General Public License v3.0
from avantifellows
def _generate_unique_slug(self):
"""Generates a unique slug based on the tag name."""
unique_slug = slug = slugify(self.name)
num = 1
while Tag.objects.filter(slug=unique_slug).exists():
unique_slug = "{}-{}".format(slug, num)
num += 1
return unique_slug
def save(self, *args, **kwargs):
3
Source : testfunc.py
with GNU General Public License v3.0
from beatonma
with GNU General Public License v3.0
from beatonma
def get_id_and_slug() -> Tuple[int, str]:
"""Create a random id and slug."""
_id = random.randint(1, 1_000_000)
slug = slugify(random_str())
return _id, slug
def create_mentionable_object(content: str = ""):
3
Source : common.py
with GNU General Public License v3.0
from bpepple
with GNU General Public License v3.0
from bpepple
def generate_slug_from_name(instance):
slug_candidate = slug_original = slugify(instance.name)
Klass = instance.__class__
for i in itertools.count(1):
if not Klass.objects.filter(slug=slug_candidate).exists():
break
slug_candidate = f"{slug_original}-{i}"
return slug_candidate
def pre_save_slug(sender, instance, **kwargs):
3
Source : issue.py
with GNU General Public License v3.0
from bpepple
with GNU General Public License v3.0
from bpepple
def generate_issue_slug(issue):
slug_candidate = slug_original = slugify(f"{issue.series.slug}-{issue.number}")
for i in itertools.count(1):
if not Issue.objects.filter(slug=slug_candidate).exists():
break
slug_candidate = f"{slug_original}-{i}"
return slug_candidate
def pre_save_issue_slug(sender, instance, *args, **kwargs):
3
Source : series.py
with GNU General Public License v3.0
from bpepple
with GNU General Public License v3.0
from bpepple
def generate_series_slug(instance):
slug_candidate = slug_original = slugify(f"{instance.name}-{instance.year_began}")
Klass = instance.__class__
for i in itertools.count(1):
if not Klass.objects.filter(slug=slug_candidate).exists():
break
slug_candidate = f"{slug_original}-{i}"
return slug_candidate
def pre_save_series_slug(sender, instance, **kwargs):
3
Source : comicimporter.py
with GNU General Public License v3.0
from bpepple
with GNU General Public License v3.0
from bpepple
def createIssueSlug(cls, pubDate, fixedNumber, seriesName):
if pubDate is not None:
slugy = seriesName + ' ' + fixedNumber + ' ' + str(pubDate.year)
else:
slugy = seriesName + ' ' + fixedNumber
new_slug = orig = slugify(slugy)
for x in itertools.count(1):
if not Issue.objects.filter(slug=new_slug).exists():
break
new_slug = f'{orig}-{x}'
return new_slug
def getComicMetadata(self, path):
3
Source : box_create.py
with MIT License
from buteco
with MIT License
from buteco
def handle(self, *args, **options):
name = slugify(options["name"].strip())
boxes = Box.objects.filter(name=name)
if boxes.count() > 0:
raise CommandError('Box "{}" already exists!'.format(name))
box = Box.objects.create_for_username(box_name=name, username=name)
box.save()
msg = "Box: {} / Token: {}".format(box.name, box.token.key)
self.stdout.write(self.style.SUCCESS(msg))
3
Source : models.py
with GNU General Public License v3.0
from CMSgov
with GNU General Public License v3.0
from CMSgov
def get_slug(self):
# don't use title because it's expensive and might cause recursion
# issues since the URL to this task might be generated when rendering the title.
from django.utils.text import slugify
return slugify(self.module.spec['title'])
def get_absolute_url(self):
3
Source : models.py
with GNU General Public License v3.0
from CMSgov
with GNU General Public License v3.0
from CMSgov
def get_absolute_url_to_question(self, question):
# The project root task displays at different URLs.
if self == self.project.root_task:
from django.utils.text import slugify
return self.project.get_absolute_url() + "#tab=" + slugify(question.spec.get("tab", ""))
else:
import urllib.parse
return self.get_absolute_url() + "/question/" + urllib.parse.quote(question.key)
def get_static_asset_url(self, asset_path, use_data_urls=False):
3
Source : snippet_models.py
with BSD 3-Clause "New" or "Revised" License
from coderedcorp
with BSD 3-Clause "New" or "Revised" License
from coderedcorp
def save(self, *args, **kwargs):
if not self.slug:
# Make a slug and suffix a number if it already exists to ensure uniqueness
newslug = slugify(self.name, allow_unicode=True)
tmpslug = newslug
suffix = 1
while True:
if not Classifier.objects.filter(slug=tmpslug).exists():
self.slug = tmpslug
break
tmpslug = newslug + "-" + str(suffix)
suffix += 1
return super().save(*args, **kwargs)
def __str__(self):
3
Source : snippet_models.py
with BSD 3-Clause "New" or "Revised" License
from coderedcorp
with BSD 3-Clause "New" or "Revised" License
from coderedcorp
def save(self, *args, **kwargs):
if not self.slug:
# Make a slug and suffix a number if it already exists to ensure uniqueness
newslug = slugify(self.name, allow_unicode=True)
tmpslug = newslug
suffix = 1
while True:
if not ClassifierTerm.objects.filter(slug=tmpslug).exists():
self.slug = tmpslug
break
tmpslug = newslug + "-" + str(suffix)
suffix += 1
return super().save(*args, **kwargs)
def __str__(self):
3
Source : utils.py
with MIT License
from codingforentrepreneurs
with MIT License
from codingforentrepreneurs
def unique_slug_generator(instance, new_slug=None):
"""
Reference post https://cfe.sh/blog/a-unique-slug-generator-for-django/
This is for a Django project and it assumes your instance
has a model with a slug field and a title character (char) field.
"""
if new_slug is not None:
slug = new_slug
else:
slug = slugify(instance.title)
Klass = instance.__class__
qs_exists = Klass.objects.filter(slug=slug).exists()
if qs_exists:
new_slug = "{slug}-{randstr}".format(
slug=slug, randstr=random_string_generator(size=4)
)
return unique_slug_generator(instance, new_slug=new_slug)
return slug
3
Source : models.py
with MIT License
from codingforentrepreneurs
with MIT License
from codingforentrepreneurs
def get_filename(self):
custom = self.name
if custom:
ext = self.get_file_ext() # .png
if custom.endswith(ext):
custom, ext = os.path.splitext(custom) # this is-my-file.png
custom = slugify(custom)
custom = f'{custom}{ext}' # this-is-my-file.png
return custom
return os.path.basename(self.key)
def get_download_url(self):
3
Source : tests.py
with MIT License
from codingforentrepreneurs
with MIT License
from codingforentrepreneurs
def test_hello_world_slug(self):
obj = Article.objects.all().order_by("id").first()
title = obj.title
slug = obj.slug
slugified_title = slugify(title)
self.assertEqual(slug, slugified_title)
def test_hello_world_unique_slug(self):
3
Source : tests.py
with MIT License
from codingforentrepreneurs
with MIT License
from codingforentrepreneurs
def test_hello_world_unique_slug(self):
qs = Article.objects.exclude(slug__iexact='hello-world')
for obj in qs:
title = obj.title
slug = obj.slug
slugified_title = slugify(title)
self.assertNotEqual(slug, slugified_title)
def test_slugify_instance_title(self):
3
Source : utils.py
with MIT License
from codingforentrepreneurs
with MIT License
from codingforentrepreneurs
def slugify_instance_title(instance, save=False, new_slug=None):
if new_slug is not None:
slug = new_slug
else:
slug = slugify(instance.title)
Klass = instance.__class__
qs = Klass.objects.filter(slug=slug).exclude(id=instance.id)
if qs.exists():
# auto generate new slug
rand_int = random.randint(300_000, 500_000)
slug = f"{slug}-{rand_int}"
return slugify_instance_title(instance, save=save, new_slug=slug)
instance.slug = slug
if save:
instance.save()
return instance
3
Source : dynamic_filenames.py
with MIT License
from codingjoe
with MIT License
from codingjoe
def slugify(value):
try: # use unicode-slugify library if installed
from slugify import slugify as _slugify
return _slugify(value, only_ascii=True)
except ImportError:
from django.utils.text import slugify as _slugify
return _slugify(value, allow_unicode=False)
class SlugFormatter(Formatter):
3
Source : views.py
with GNU General Public License v3.0
from CyberHavenProgramming
with GNU General Public License v3.0
from CyberHavenProgramming
def create(request, category_slug):
category = FundraiserCategory.objects.get(slug=category_slug)
form = FundraiserForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
new_fundraiser = form.save(commit=False)
new_fundraiser.slug = slugify(request.POST['title'])
new_fundraiser.user = request.user
new_fundraiser.category = category
new_fundraiser.save()
return redirect(reverse('fundraiser_app:detail', args=[new_fundraiser.category.slug, new_fundraiser.id, new_fundraiser.created.year, new_fundraiser.created.month, new_fundraiser.created.day, new_fundraiser.slug]))
return render(request, 'fundraiser_app/fundraiser_create.html', {'form': form, 'category_slug': category_slug})
def detail(request, category_slug, fundr_id, year, month, day, slug): # show detail for Fundraiser, and all FundraiserMsgUpdate's
3
Source : models.py
with MIT License
from diyajaiswal11
with MIT License
from diyajaiswal11
def save(self, *args, **kwargs):
self.slug = slugify(self.title, allow_unicode=True)
super().save(*args, **kwargs)
for tag in self.tags.all():
tag_dict,_ = TagDict.objects.get_or_create(tag=str(tag))
tag_dict.count += 1
tag_dict.save()
def get_absolute_url(self):
3
Source : models.py
with GNU Affero General Public License v3.0
from Dwarni
with GNU Affero General Public License v3.0
from Dwarni
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
self.slug = slugify(self.name)
super().save(force_insert, force_update, using,
update_fields)
def __str__(self):
3
Source : 0004_auto_20180912_2138.py
with GNU Affero General Public License v3.0
from Dwarni
with GNU Affero General Public License v3.0
from Dwarni
def update_region_slugs(apps, schema_editor):
"""
Update the slug fields of all regions which have 'blub' as slug.
"""
Region = apps.get_model('regions', 'Region')
for region in Region.objects.filter(slug='blub'):
region.slug = slugify(region.name)
region.save()
class Migration(migrations.Migration):
3
Source : contract.py
with GNU Affero General Public License v3.0
from elixir-luxembourg
with GNU Affero General Public License v3.0
from elixir-luxembourg
def clean_key(self):
data = self.cleaned_data['key']
return slugify(data)
class PartnerRoleForm(ModelForm):
3
Source : wagtailcustom_tags.py
with GNU Affero General Public License v3.0
from entrepreneur-interet-general
with GNU Affero General Public License v3.0
from entrepreneur-interet-general
def add_id_attribute(match):
"""
This is a regexp replacement function that takes
in the above regex match results, and then turns:
< h1>some text < /h1>
Into:
< h1 id="some-text">some text < /h1>
where the id attribute value is generated by running
the heading text through Django's slugify() function.
"""
n = match.group(1)
text_content = match.group(2)
heading_id = slugify(text_content)
return f' < h{n} id="{heading_id}">{text_content} < /h{n}>'
def with_heading_ids(self):
3
Source : models.py
with MIT License
from erickmbugua
with MIT License
from erickmbugua
def save(self,*args,**kwargs):
value=self.name
self.slug=slugify(value,allow_unicode=True)
super().save(*args,**kwargs)
class Comment(models.Model):
3
Source : models.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def get_achievement_image_upload_path(instance, filename):
# Obtain extension
# NB: A file can be renamed to have ANY extension
_, extension = os.path.splitext(filename)
# file will be uploaded to MEDIA_ROOT / images/achievement_ < achievement_id>. < file_extension>
return 'images/achievements/achievement_{0}{1}'.format(slugify(instance.name), extension)
# Achievements that can be earned by users
class Achievement(models.Model):
3
Source : models.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def get_image_upload_path(instance, filename):
# Obtain extension
# NB: A file can be renamed to have ANY extension
_, extension = os.path.splitext(filename)
# file will be uploaded to MEDIA_ROOT / presets/ < achievement_id>. < file_extension>
return 'images/presets/{0}{1}'.format(slugify(instance.name), extension)
class PresetImageManager(models.Manager):
3
Source : models.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def get_item_image_upload_path(instance, filename):
# Obtain extension
# NB: A file can be renamed to have ANY extension
_, extension = os.path.splitext(filename)
item_name = f'{instance.id}-{slugify(instance.name)}'
# file will be uploaded to MEDIA_ROOT / images/item/ < item_type>/ < id>. < file_extension>
return 'images/item/{type_str}/{item_name}{extension}'.format(
type_str=slugify(instance.__class__.__name__),
item_name=item_name,
extension=extension,
)
class Item(models.Model):
See More Examples