I have a django charField that is checked via the is_valid() method. The user is supposed to enter a valid logical expression in this field, so I wrote a parsing method that raises an exception if the expression is not correct.
How can I enhance the is_valid() method to cover this exception and display an error message to the user that his query was wrong?
I read this article (https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute) but still have no idea how to do that.
try:
job = Job(user=request.user) # set the current user
form = JobForm(request.POST, instance=job)
if form.is_valid():
form.save()
job.execute()
messages.success(request, u'A new job with the query "{query}" was created.'.format(query=job.query))
return HttpResponseRedirect(reverse('job-index'))
return self.render_to_response({'job_form': form, 'is_new': True})
except ParseError:
return self.render_to_response({'job_form': form, 'is_new': True})
The try…except-Block should be done within the is_valid() method, that is my intention. Someone got any hints?
You’ve provided an answer to the question yourself – you create your own form (or model form) and perform custom validation on that form’s field using its
clean_'fieldname'()method. So for example, say your model is:you create a
forms.py:then make use of it in your
views.pyas you already are in your example. Now if the value the user enters doesn’t meet your criteria, an exception will be automatically raised