| | 1 | Validation for unique slugs. |
| | 2 | |
| | 3 | Requires a minor change to the admin view. |
| | 4 | |
| | 5 | {{{ |
| | 6 | |
| | 7 | --- django/contrib/admin/views/main.py (revision 3185) |
| | 8 | +++ django/contrib/admin/views/main.py (working copy) |
| | 9 | @@ -319,7 +319,7 @@ |
| | 10 | |
| | 11 | if request.POST: |
| | 12 | new_data = request.POST.copy() |
| | 13 | - |
| | 14 | + new_data.update({'id':object_id}) |
| | 15 | if opts.has_field_type(models.FileField): |
| | 16 | new_data.update(request.FILES) |
| | 17 | |
| | 18 | |
| | 19 | }}} |
| | 20 | |
| | 21 | someapp/models.py |
| | 22 | |
| | 23 | {{{ |
| | 24 | |
| | 25 | class isUniqueSlug: |
| | 26 | |
| | 27 | def __init__(self, slug, app, model): |
| | 28 | self.slug, self.app, self.model = slug, app, model |
| | 29 | |
| | 30 | def __call__(self, field_data, all_data): |
| | 31 | |
| | 32 | from django.core.validators import ValidationError |
| | 33 | from django.utils.translation import gettext, gettext_lazy |
| | 34 | from django.db.models.loading import get_model |
| | 35 | |
| | 36 | model = get_model(self.app,self.model) |
| | 37 | |
| | 38 | if all_data.get('id', None): |
| | 39 | q=model.objects.exclude(id=all_data.get('id')) |
| | 40 | else: |
| | 41 | q=model.objects.all() |
| | 42 | |
| | 43 | try: |
| | 44 | d = {self.slug+'__exact': field_data} |
| | 45 | p = q.get(**d) |
| | 46 | except: |
| | 47 | p=None |
| | 48 | |
| | 49 | if p: |
| | 50 | raise ValidationError, gettext_lazy("Is not a unique slug.") |
| | 51 | |
| | 52 | |
| | 53 | class Somemodel(models.Model): |
| | 54 | |
| | 55 | any_slug = models.SlugField(validator_list=[isUniqueSlug('any_slug','someapp','Somemodel')]) |
| | 56 | |
| | 57 | }}} |
| | 58 | |
| | 59 | |