1

I've put together a basic CMS system for a project and I'm adding an order system so that you can order the created pages in the nav bar. Unfortunately the custom validator I've written is a little to aggressive and raises and error when you edit a page because, correctly, the order already exists in the database.

Model the form is based on:

class Page(models.Model):
page_name = models.CharField(max_length=100)
page_content = models.CharField(max_length=16777000)
link = models.URLField(blank=True)
order = models.IntegerField()

Custom Validator:

def clean_order(self):
    data = self.cleaned_data['order']
    pg = Page.objects.filter(order=data)
    if pg.count() > 0:
        raise forms.ValidationError("This order number already exists. Use another.")
    return data

Is there any way for me to, upon performing the update, have the custom validator only raise an error if the new order already exists BUT where it is not current Page object. Something like:

pg = Page.objects.filter(order=data).filter(pk!=editpagepk)

Thanks!

3 Answers 3

3

Use the exclude method, like so:

pg = Page.objects.filter(order=data).exclude(pk=self.instance.pk)
Sign up to request clarification or add additional context in comments.

Comments

1

Use Django queryset's exclude to exclude the current object from the results. Assuming you have an id field in the Page model acting as a primary key:

def clean_order(self):
    order = self.cleaned_data['order']
    pg = Page.objects.filter(order=order).exclude(id=self.instance.id)
    if pg.count() > 0:
        raise forms.ValidationError(" ... ")
    return data

The above assumes you're using a ModelForm, because that's what you need to find the current object instance being submitted via POST at self.instance. More details about this last point here.

Comments

0

I guess you could try to query the matching object and catch the exception:

try:
    Page.objects.filter(order=data).get(pk=editpagepk)
except Page.DoesNotExist:
    raise forms.ValidationError("...")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.