Version 3 (modified by [530], 18 years ago) ( diff )

--

Validation for unique slugs.

Requires a minor change to the admin view.

--- django/contrib/admin/views/main.py  (revision 3185)
+++ django/contrib/admin/views/main.py  (working copy)
@@ -319,7 +319,7 @@

     if request.POST:
         new_data = request.POST.copy()
-
+        new_data.update({'id':object_id})
         if opts.has_field_type(models.FileField):
             new_data.update(request.FILES)


someapp/models.py

class isUniqueSlug:

    def __init__(self, slug, app, model):
        self.slug, self.app, self.model = slug, app, model

    def __call__(self, field_data, all_data):

        from django.core.validators import ValidationError
        from django.utils.translation import gettext, gettext_lazy
        from django.db.models.loading import get_model

        model = get_model(self.app,self.model)

        if all_data.get('id', None):
            q=model.objects.exclude(id=all_data.get('id'))
        else:
            q=model.objects.all()

        try:
            d = {self.slug+'__exact': field_data}
            p = q.get(**d)
        except:
            p=None

        if p:
            raise ValidationError, gettext_lazy("Is not a unique slug.")


class Somemodel(models.Model):

    any_slug = models.SlugField(validator_list=[isUniqueSlug('any_slug','someapp','Somemodel')])

Note: See TracWiki for help on using the wiki.
Back to Top