如何在我的Django的views.py中提出ValidationError(或做类似的事情)? [英] How do I raise a ValidationError (or do something similar) in views.py of my Django?
问题描述
def clean_title(self):
title = self.cleaned_data [' title']
if len(title)< 5:
raise forms.ValidationError(标题必须超过5个字符)
返回标题
但是,有些事情需要在 views.py
中进行验证。例如...是用户最后一次在一分钟前发布的内容?
这种东西需要request.user,模型层无法获取。所以,我必须在views.py中验证。如何在views.py中执行某些操作呢?
raise forms.ValidationError(标题必须超过5个字符)
我认为gruszczy的答案是一个很好的答案,但如果你经过泛型验证涉及变量,你认为只在视图中可用,这里有一个替代方法:将vars作为参数传递给表单,并以表单的main()方法处理它们。
这里的区别/优点是,您的观点保持简单,与表单内容相关的所有内容都可以接受。
例如:
#在您的VIEW
#pass request.user作为关键字参数窗体
myform = MyForm(user = request.user)
#在您的forms.py
#顶部:
从myapp.foo.bar导入ok_to_post#一些抽象的实用程序你写速率限制发布
#和你的特定表单定义
类MyForm(forms.Form)
...你的字段在这里...
def __init __(self,* args,** kwargs):
self.user = kwargs.pop( 'user')#缓存您传递的用户对象
super(MyForm,self).__ init __(* args,** kwargs)#并继续初始化
def clean(self):
#通过传入缓存的用户对象来测试速率限制
如果不是ok_to_post(self.user):#使用你的节流实用程序
raise forms.ValidationError(你不能每x分钟发一次)
return self.cleaned_data#永远不会忘记这个! ; o)
请注意,提出一个通用的 ValidationError
在 clean()
方法将错误放入 myform.non_field_errors
,所以你必须确保您的模板包含 {{form.non_field_errors}}
如果您手动显示您的表单
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:
# 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
这篇关于如何在我的Django的views.py中提出ValidationError(或做类似的事情)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!