create unique slug django

create unique slug django

By : user2950931
Date : November 17 2020, 11:58 AM
Hope that helps I have a problem with creating unique slugs using django models. I want to allow the admin user to change the slug from the edit page in the admin. When a slug already exists there should be "slug + _1", "slug + _2" etc. Also when a new page is created and there is no slug given the slug should be the page title. I have this code but for some reason the admin keeps saying "Page with this Slug already exists." when I add a page with a slug that already exists. Hope somebody can help me , Try this. Didn't test it myself. But it should give you the idea.
code :
import re
def save(self, *args, **kwargs):
    if not self.id: # Create
        if not self.slug: # slug is blank
            self.slug = slugify(self.page_title)
        else: # slug is not blank
            self.slug = slugify(self.slug)
    else: # Update
        self.slug = slugify(self.slug)

    qsSimilarName = Page.objects.filter(slug__startswith='self.slug')

    if qsSimilarName.count() > 0:
        seqs = []
        for qs in qsSimilarName:
            seq = re.findall(r'{0:s}_(\d+)'.format(self.slug), qs.slug)
            if seq: seqs.append(int(seq[0]))

        if seqs: self.slug = '{0:s}_{1:d}'.format(self.slug, max(seqs)+1)

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

Share : facebook icon twitter icon
How to create a unique slug in Django

How to create a unique slug in Django

By : user2332773
Date : March 29 2020, 07:55 AM
it fixes the issue I use this snippet for generating unique slug and my typical save method look like below
slug will be Django SlugField with blank=True but enforce slug in save method.
code :
def save(self, **kwargs):
    slug_str = "%s %s" % (self.title, self.us_zip) 
    unique_slugify(self, slug_str) 
    super(Need, self).save(**kwargs)
Unique slugs that, if fits with slug-1, slug-2... slug-n

Unique slugs that, if fits with slug-1, slug-2... slug-n

By : Joe
Date : March 29 2020, 07:55 AM
this one helps. Don't just check if that identical slug is present. Use a regular expression to count all the slugs that follow the pattern /()(-\d+)?/. Because you only allow alphanumerics your base regex above will be the slug itself.
Django Unique Slug by id

Django Unique Slug by id

By : Nithya sreedharan
Date : March 29 2020, 07:55 AM
With these it helps Of course you can simply overwrite save() method on model (or make receiver for post_save signal). It will be something like:
code :
from django.template.defaultfilters import slugify

class Deal(models.Model):
product = models.ForeignKey(Product)
slug = models.SlugField(max_length=255, unique=True)

    def save(self, *args, **kwargs):
        super(Deal, self).save(*args, **kwargs)
        if not self.slug:
            self.slug = slugify(self.product.title) + "-" + str(self.id)
Generating unique slug in Django

Generating unique slug in Django

By : chengkande
Date : March 29 2020, 07:55 AM
Hope that helps I ended up using This Django Snippet to over-ride the save method of Phone in my models.py:
code :
def save(self, **kwargs):
    slug_str = "%s %s %s %s" % (self.user, self.year, self.model, self.series)
    unique_slugify(self, slug_str)
    super(Phone, self).save()
How I should testing Django views with unique slug

How I should testing Django views with unique slug

By : Fida
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , In tests.py self currently refers to the class PostDetailTestCase and that class has no slug. You've almost created a post in the db that django can access.
What you need to do however is to use the following. You need to use the objects.create method in the following way.
code :
test = Post.objects.create(
response = self.client.get(reverse('board_detail', args=(test.slug,)))
Related Posts Related Posts :
  • Return new instance of subclass when using methods inherited from parent class in Python
  • Which function in django.contrib.auth creates the default model permissions?
  • Formatting text in tabular form with Python
  • How to determine the first day of a month in Python
  • Error while converting date to timestamp in python
  • Python string iterations
  • Is there any file number limitation when you select multiple files with wxFileDialog?
  • Errors with Matplotlib when making an executable with Py2exe (Python)
  • Django Haystack - Indexing single field
  • Go Pro Hero 3 - Streaming video over wifi
  • Appending a column in .csv with Python/Pandas
  • How to change my result directory in Robot framework using RIDE?
  • problem with using pandas to manipulate a big text file in python
  • python-magic module' object has no attribute 'open'
  • Where goes wrong for this High Pass Filter in Python?
  • Why inserting keys in order into a python dict is faster than doint it unordered
  • flann index saving in python
  • Create new instance of list or dictionary without class
  • How can I easily convert FORTRAN code to Python code (real code, not wrappers)
  • Address of lambda function in python
  • Python adding space between characters in string. Most efficient way
  • python http server, multiple simultaneous requests
  • Disguising username & password on distributed python scripts
  • Post GraphQL mutation with Python Requests
  • Why doesnt pandas create an excel file?
  • Rolling comparison between a value and a past window, with percentile/quantile
  • How to avoid repetitive code when defining a new type in python with signature verification
  • How to configure uWSGI in order to debug with pdb (--honour-stdin configuration issue)
  • In Python, how do you execute objects that are functions from a list?
  • Python- Variable Won't Subtract?
  • Processing Power In Python
  • Python 2.7.2 - Cannot import name _random or random from sys
  • Why doesn't the Python sorted function take keyword order instead of reverse?
  • Make a function redirect to other functions depending on a variable
  • get_absolute_url in django-categories
  • Monitoring non-Celery background task with New Relic in Python
  • Feature selection with LinearSVC
  • LSTM - Predicting the same constant values after a while
  • Test the length of elements in a list
  • Django: render radiobutton with 3 columns, cost column must change according to size & quantity selected
  • Python class attributes vs global variable
  • sys.stdout.writelines("hello") and sys.stdout.write("hello")
  • is ndarray faster than recarray access?
  • Python - search through directory trees, rename certain files
  • GAE: How to build a query where a string begins with a value
  • TypeError: __init__() takes at least 2 arguments (1 given)
  • Overriding and customizing "django.contrib.auth.views.login"
  • Django : Redirect to a particular page after login
  • Python search and copy files in directory
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • Install python-numpy in the Virtualenv environment
  • `.select_by_visible_text()` is failed to select element?
  • Unable to send data multiple requests in a single connection — socket error
  • Pandas HDFStore unload dataframe from memory
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org