Lester Burnham
Lester Burnham

Reputation: 181

How to process Django validation errors

I'm having some trouble grokking Django forms and validation.

#views.py:
def create(request):
    if request.method == 'POST':
        form = CreateDocumentForm(request.POST)
        if form.is_valid():
            doc = Document.objects.create(name=form.cleaned_data['name'])
    #snip


#forms.py:
    class CreateDocumentForm(forms.ModelForm):
    name = forms.CharField()
    def clean_name(self):
        cleaned_name = self.cleaned_data['name']
        rgx = re.compile('^(\w|-|\.)+$')
        if rgx.match(cleaned_name) == None:
            raise ValidationError("invalidchars")
        return cleaned_name

The logic is working properly, but I don't know how to tell which kind of VaidationError was raised. Also - This is handled by an Ajax request, so I won't be using templating in the repsonse. I need to get the status of what failed in this view.

thx

Upvotes: 2

Views: 780

Answers (1)

Ian Clelland
Ian Clelland

Reputation: 44132

You generally won't see the ValidationErrors themselves. If you call form.is_valid, then the errors that occur during validation are all collected and returned to you as a dictionary, form.errors

You can check that dictionary for errors relating to any specific field. The result for any field with errors should be the string value of any ValidationErrors that were raised for that field.

In your view, then, if form.is_valid() returns False, then you can do this:

if 'name' in form.errors:
    for err_message in form.errors['name']:
        # do something with the error string

Upvotes: 4

Related Questions