我正在使用 Django 表单。我在模型层进行验证:
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
但是,我需要在 views.py
中验证一些内容。例如...用户上一次发布内容是在一分钟前吗?
那种东西需要request.user,模型层无法获取。所以,我必须在views.py 中进行验证。我如何在 views.py 中做一些事情来做这样的事情?
raise forms.ValidationError("Headline must be more than 5 characters.")
最佳答案
我认为 gruszczy 的答案是一个很好的答案,但是如果您在进行涉及您认为仅在 View 中可用的变量的通用验证之后,这里有一个替代方法:将 vars 作为参数传递给表单并在表单的主要 clean() 方法。
这里的区别/优势是您的 View 保持简单,并且与可接受的表单内容相关的所有事情都发生在表单中。
例如:
# 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)
请注意,在 clean()
方法中引发通用 ValidationError
会将错误放入 myform.non_field_errors
中,因此您必须如果您手动显示表单,请确保您的模板包含 {{form.non_field_errors}}
关于python - 如何在 Django 的 views.py 中引发 ValidationError(或执行类似操作)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4482392/