本文介绍了is_valid()vs clean()django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在找到验证我的django表单的方法的过程中,我在django文档中遇到了两种方法is_valid()和clean()。任何人都可以启发我们他们是如何不同/相同的?



谢谢。

解决方案

is_valid()自动在表单上调用 clean()。您的视图中使用 is_valid(),您的表单类中使用 clean()



您的 clean()函数将返回 self.cleaned_data 如果你会注意到在下面的视图中不能作为程序员处理。

  form = myforms.SettingsForm(request.POST)
如果form.is_valid():
name = form.cleaned_data ['name']
#do stuff

您不需要执行 clean_data = form.is_valid(),因为 is_valid()将调用清理并覆盖要清理的表单对象中的数据。所以你的如果form.is_valid()块中的所有内容将是干净和有效的。您的块中的名称字段将是消毒版本,不一定是 request.POST 中的内容。



更新
您还可以显示错误消息。在 clean()中,如果表单数据无效,您可以在这样的字段上设置错误消息:

  self._errors ['email'] = [u'Email已经在使用中] 

现在 is_valid()将返回False,所以在其他块中,您可以用覆盖的表单对象重新显示页面,它将显示如果您的模板使用错误字符串,则显示错误消息。


In the process of finding a way to validate my django forms, I came across two methods is_valid() and clean() in the django docs. Can anyone enlighten me the how they are different/same? What are the pros and cons of either?

Thanks.

解决方案

is_valid() calls clean() on the form automatically. You use is_valid() in your views, and clean() in your form classes.

Your clean() function will return self.cleaned_data which if you will notice in the following view is not handled by you as the programmer.

form = myforms.SettingsForm(request.POST)
if form.is_valid():
   name = form.cleaned_data['name']
   #do stuff

You didn't have to do clean_data = form.is_valid() because is_valid() will call clean and overwrite data in the form object to be cleaned. So everything in your if form.is_valid() block will be clean and valid. The name field in your block will be the sanitized version which is not necessarily what was in request.POST.

UpdateYou can also display error messages with this. In clean() if the form data isn't valid you can set an error message on a field like this:

self._errors['email'] = [u'Email is already in use']

Now is_valid() will return False, so in the else block you can redisplay the page with your overwritten form object and it will display the error message if your template uses the error string.

这篇关于is_valid()vs clean()django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 21:09