Python 如何在我的 Django 的 views.py 中引发 ValidationError (或做类似的事情)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4482392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I raise a ValidationError (or do something similar) in views.py of my Django?
提问by TIMEX
I'm using Django forms. I'm validating in the model layer:
我正在使用 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
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?
但是,我需要在views.py. 例如......用户最后一次发布内容是在一分钟前吗?
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?
那种东西需要 request.user ,而模型层无法获得。所以,我必须在views.py 中进行验证。我如何在 views.py 中做一些事情来做这件事?
raise forms.ValidationError("Headline must be more than 5 characters.")
采纳答案by Steve Jalim
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.
我认为 gruszczy 的答案是一个很好的答案,但是如果您在进行涉及您认为仅在视图中可用的变量的通用验证之后,这里有一个替代方法:将 vars 作为参数传递给表单并在表单的主要内容中处理它们清洁()方法。
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 ValidationErrorin the clean()method will put the error into myform.non_field_errorsso you'll have to make sure that your template contains {{form.non_field_errors}}if you're manually displaying your form
请注意,ValidationError在clean()方法中引发泛型会将错误放入其中,myform.non_field_errors因此{{form.non_field_errors}}如果您手动显示表单,则必须确保您的模板包含
回答by gruszczy
You don't use ValidationErrorin 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. ValidationErrorshould be raised inside a Forminstance, when input data doesn't validate. This is not the case.
您不在ValidationError视图中使用,因为这些例外与表单一样。相反,您应该将用户重定向到其他一些 url,这将向他解释,他不能很快再次发布。这是处理这些东西的正确方法。当输入数据未验证时,ValidationError应该在Form实例内引发。不是这种情况。
回答by ThomasAFink
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/
文档:https: //docs.djangoproject.com/es/1.9/ref/contrib/messages/

