Nick B Nick B - 1 year ago 140
Python Question

Generating unique slug in Django

I have seen a variety of different methods for generating unique slugs: Ex. 1, Ex.2, Ex. 3, Ex. 4, etc. etc.

I want to create unique slugs upon saving a ModelForm. If my models are like:

class Phone(models.Model):
user = models.ForeignKey(User)
slug = models.SlugField(max_length=70, unique=True)
year = models.IntegerField()
model = models.ForeignKey('Model')
series = models.ForeignKey('Series')

Say that the
object has the following values (via submitted ModelForm):

Phone.user = dude
Phone.year = 2008
Phone.model = iphone
Phone.series = 4S

I want the url for this object to appear like:

I understand that I should use
via either signals or over-riding the save method to make this happen. But if user
creates a second 2008 iphone 4S object, what the best way to create a unique slug for this object? I want the additional objects's url to look like:

#...etc ...

After googling, it seems like there are a variety of different methods for creating slugs in django, which has been confusing when trying to figure out best practices.

Thanks a lot for any advice and clarification on this issue!

Answer Source

I ended up using This Django Snippet to over-ride the save method of Phone in my

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()

But thanks to jpic for the contribution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download