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

时间:2010-12-19 09:56:06

标签: python django validation forms

我正在使用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.")

3 个答案:

答案 0 :(得分:16)

我认为gruszczy的答案很好,但是如果你在涉及你认为只在视图中可用的变量的泛型验证之后,这里有另一种选择:将变量作为参数传递给表单并在其中处理它们表单的主要clean()方法。

这里的差异/优势是您的视图更简单,并且表格内容可接受的所有内容都在表单中。

例如:

# 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)

请注意,在ValidationError方法中引发通用clean()会将错误放入myform.non_field_errors,因此如果您需要确保模板中包含{{form.non_field_errors}} '手动显示表单

答案 1 :(得分:6)

您不会在视图中使用ValidationError,因为这些例外与表单有关。相反,你应该将用户重定向到其他网址,这将向他解释,他不能很快再次发布。这是处理这些东西的正确方法。当输入数据未验证时,应在ValidationError实例内引发Form。事实并非如此。

答案 2 :(得分:4)

您可以在视图中使用消息:

from django.contrib import messages

messages.error(request, "Error!")

文档:https://docs.djangoproject.com/es/1.9/ref/contrib/messages/

相关问题