I'm using Django forms. I'm validating in the model layer:
def clean_title(self):
title = self.cleaned_data['title']
if len(title) < 5:
raise forms.ValidationError("Headline must be more than 5 characters.")
return title
However, there are some things that I need to validate in the views.py
. For example...was the last time the user posted something more than a minute ago?
That kind of stuff requires request.user, which the models layer cannot get. So, I must validate in the views.py. How do I do something in the views.py to do the exact thing as this?
raise forms.ValidationError("Headline must be more than 5 characters.")
I think gruszczy's answer is a good one, but if you're after generic validation involving variables that you think are only available in the view, here's an alternative: pass in the vars as arguments to the form and deal with them in the form's main clean() method.
The difference/advantage here is that your view stays simpler and all things related to the form content being acceptable happen in the form.
eg:
Note that raising a generic
ValidationError
in theclean()
method will put the error intomyform.non_field_errors
so you'll have to make sure that your template contains{{form.non_field_errors}}
if you're manually displaying your formYou don't use
ValidationError
in views, as those exceptions as for forms. Rather, you should redirect the user to some other url, that will explain to him, that he cannot post again that soon. This is the proper way to handle this stuff.ValidationError
should be raised inside aForm
instance, when input data doesn't validate. This is not the case.You can use messages in views:
Documentation: https://docs.djangoproject.com/es/1.9/ref/contrib/messages/