2

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

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

And since this is an Ajax request. you can send the error dictionary (perhaps converted to JSON) back as the response.
ha. I actually just came back to report that I figured this out - however - forms.errors['name'] contains the string that was passed to the ValidatioError constructor wrapped in markup: <ul class="errorlist"><li>invalidchars</li></ul>. How can I get just the error? Also - am i doing this right, or is there a better (preferred) way?
The unicode method for form.errors['name'] gives the html markup, but if you loop through form.errors['name'] as Ian suggests, you'll get a list of the error strings. In your example, there is only one error string in the list, which you can see with f.errors['name'][0].

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.