24

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.")
2
  • 1
    That doesn't look like validating in the model layer (as in the django.db.models.Model. Do you mean the django.forms.Form/ModelForm layer? I guess so Dec 19, 2010 at 10:02
  • I have a similar requirement for a different reason: there's a field that's only sometimes required, depending on the page, so the view needs to enforce it as it's tightly coupled to the page.
    – Rob Grant
    Jul 31, 2014 at 7:14

3 Answers 3

27

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:

# IN YOUR VIEW 
# pass request.user as a keyword argument to the form
myform = MyForm(user=request.user)


# IN YOUR forms.py
# at the top:

from myapp.foo.bar import ok_to_post # some abstracted utility you write to rate-limit posting 

# and in your particular Form definition

class MyForm(forms.Form)

   ... your fields here ...

   def __init__(self, *args, **kwargs):
      self.user = kwargs.pop('user')  # cache the user object you pass in
      super(MyForm, self).__init__(*args, **kwargs)  # and carry on to init the form


   def clean(self):
      # test the rate limit by passing in the cached user object

      if not ok_to_post(self.user):  # use your throttling utility here
          raise forms.ValidationError("You cannot post more than once every x minutes")

      return self.cleaned_data  # never forget this! ;o)

Note that raising a generic ValidationError in the clean() method will put the error into myform.non_field_errors so you'll have to make sure that your template contains {{form.non_field_errors}} if you're manually displaying your form

3
  • Great solution. Is this a hack? I love it though, ty
    – TIMEX
    Dec 19, 2010 at 12:42
  • No, I'd not call it a hack. It's just leveraging the Django Form classes more than the default/tutorial approach. I've used it plenty of places and (as long as you are aware of what pop() will do, in that it removes the keyword argument from kwargs, there's nothing to catch you out. If you don't want to remove it from kwargs, use get() instead. Dec 19, 2010 at 12:46
  • Nice! By your solution, I could pass the request object on the form so I could check the text content of the uploaded file. Jun 25, 2021 at 13:49
9

You 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 a Form instance, when input data doesn't validate. This is not the case.

1
  • 3
    I think this is a good approach, but from a usability point of view it'd be even better to just add that message as a flash/django.contrib.messages message and not redirect to a new page, but just render the filled-out form again. That way, the user can wait, say, 50 seconds, and submit the data again, without having to retype it all Dec 19, 2010 at 10:17
4

You can use messages in views:

from django.contrib import messages

messages.error(request, "Error!")

Documentation: https://docs.djangoproject.com/es/1.9/ref/contrib/messages/

2
  • Messages is a simple effective solution for a simple form error.
    – MagicLAMP
    Jan 7, 2017 at 20:22
  • 1
    but how to apply messages when you in forms.py?
    – Romeo
    Jul 1, 2018 at 9:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.