New field type which allows prepopulate_from to work not only from javascript but in python too. If the slugfield has unique=True creates a unique slug too.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | from django.db.models import fields
from django.template.defaultfilters import slugify
def unique_slug(model, slug_field, slug_value):
orig_slug = slug = slugify(slug_value)
index = 0
while True:
try:
model.objects.get(**{slug_field: slug})
index += 1
slug = orig_slug + '-' + str(index)
except model.DoesNotExist:
return slug
class AutoSlugField(fields.SlugField):
def pre_save(self, model_instance, add):
if self.prepopulate_from:
if self.unique:
return unique_slug(model_instance.__class__, self.name, getattr(model_instance, self.prepopulate_from[0]))
else:
return slugify(getattr(model_instance, self.prepopulate_from[0]))
else:
return super(AutoSlugField, self).pre_save(model_instance, add)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
slug = models.SlugField(unique=True,prepopulate_from=('title',))
not enough ?
#
This would make it easier to do automated testing. Slug fields have always errored out for me, and this snippet looks like it would address that.
#
@kujemanee Using a simple SlugField the values is prepopulated only in the admin interface trough javascript. Using AutoSlugField the value is automatically retrieved by each saving if necessary and adapted to be unique
#
setattr(model_instance, slug_field, slug)
before returning the slug value would be nice too, otherwise new instances of the model created do not have it set, for that request at least, although persists just fine to the db.
Wasted an hour cause of this! :) Thanks for the snippet!
#
Please login first before commenting.