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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…