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

TIM*_*MEX 17 python forms django validation

我正在使用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
Run Code Online (Sandbox Code Playgroud)

但是,有一些事情我需要在中进行验证views.py.例如......是用户最后一次发布超过一分钟的内容吗?

这种东西需要request.user,模型层无法获取.所以,我必须在views.py中验证.我如何在views.py中做一些事情来做到这一点?

raise forms.ValidationError("Headline must be more than 5 characters.")
Run Code Online (Sandbox Code Playgroud)

Ste*_*lim 17

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

请注意,ValidationErrorclean()方法中引发泛型会将错误放入,myform.non_field_errors因此{{form.non_field_errors}}如果您手动显示表单,则必须确保模板包含


gru*_*czy 6

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

  • 我认为这是一个很好的方法,但从可用性的角度来看,最好将该消息添加为 flash/django.contrib.messages 消息并且*不*重定向到新页面,而只是渲染再次填写表格。这样,用户可以等待,比如说,50 秒,然后再次提交数据,而无需重新输入所有数据 (3认同)

Tho*_*ink 5

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

from django.contrib import messages

messages.error(request, "Error!")
Run Code Online (Sandbox Code Playgroud)

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