简体   繁体   English

如何在Django的views.py中引发ValidationError(或类似的东西)?

[英]How do I raise a ValidationError (or do something similar) in views.py of my Django?

I'm using Django forms. 我正在使用Django表单。 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 . 但是,我需要在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. 这种东西需要request.user,模型层无法获取。 So, I must validate in the views.py. 所以,我必须在views.py中验证。 How do I do something in the views.py to do the exact thing as this? 我如何在views.py中做一些事情来做到这一点?

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. 我认为gruszczy的答案很好,但是如果你在涉及你认为只在视图中可用的变量的泛型验证之后,这里有另一种选择:将vars作为参数传递给表单并以表格的形式处理它们clean()方法。

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 请注意,在clean()方法中引发通用ValidationError会将错误放入myform.non_field_errors因此如果您手动显示表单,则必须确保模板包含{{form.non_field_errors}}

You don't use ValidationError in views, as those exceptions as for forms. 您不在视图中使用ValidationError ,因为这些例外与表单一样。 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. 当输入数据未验证时,应在Form实例内引发ValidationError This is not the case. 不是这种情况。

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/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Django中,如何访问views.py中的模板值? - In Django, how do I access template values in the views.py? 我如何在模板上显示我的 views.py 输出 - How do i display my views.py output on a template 如何从 Django 中的 views.py 获取变量并将其显示在我的 HTML 页面上 - How do I take a variable from views.py in Django and display it on my HTML page 在Django中,如何将表格错误放入views.py中? - In Django, how do I put a form error into my views.py? 我该如何编码views.py,以便表单数据存储在数据库(/ admin)中? 使用Django(v2) - How do I code my views.py such that the form data gets stored in my database(/admin)? Using Django (v2) 如何将自定义类导入 Django views.py? - How do you import custom classes into Django views.py? 如何在django views.py中获取选定选项的文本值 - How do I get the text value of a selected option in django views.py 如何在 django views.py 中的单个变量或列表中存储多个值? - How do I store multiple values in a single variable or list in django views.py? 使用feedparser / RSS,如何在Django中将feed对象从views.py传递到.html? - Using feedparser/RSS, how do I pass the feed object from views.py to .html in django? 如何在数据库 class 上运行 function 而不是 Z2B9AFB89A6ACC1075B159BFCA3 中的 views.py 中的 class - How do I run function on database class rather than class in views.py in django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM