Django:表单创建时的表单验证错误 [英] Django: form validation errors on form creation

查看:91
本文介绍了Django:表单创建时的表单验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个使用ChoiceField的Django表单:

  class MyForm(forms.Form):
名称= Forms.CharField(label = Name,required = True)
some_object = forms.ChoiceField(label = Object,choices = [(0,'-----')] + [(x .id,x.name)for Obj.objects.all()])x

Choisefield是用空选择为首的对象列表初始化。没有对象的pk = 0。
以这种形式,我有一个clean()方法:

  def clean(self):
如果不是Obj.objects.filter(self.cleaned.data ['some_object']。exists():
self.errors.update({'some_object':['无效选择']})

当我向服务器发送表单时,如果其中的数据与条件不匹配,则此方法效果很好。 is_valid返回False,我用错误消息呈现表单。但是,当我创建一个空表单时,像这样:

  if request.method =='GET':
data = {'name':'Untitled',
'some_object':0}
form = MyForm(data)
return render(request, 'app\template.html',{'form':form})

Django使用以下方式渲染表单错误消息(无效选择),即使刚刚创建了表单并且打算将对象选择设置为空位置。在特定情况下是否可以禁用表单clean()方法呢?或者我正在做所有这些事情错了吗练习创建空表格吗?

解决方案

问题是带有任何数据字典的表格都算作绑定表单,Django将针对该表单执行数据验证。详情请参阅此处: https:// docs.djangoproject.com/zh-CN/2.1/ref/forms/api/#bound-and-unbound-forms



您想要未绑定表单-要在此处具有默认初始值,只需在表单字段上设置 initial 属性。在此处查看完整的详细信息: https://docs.djangoproject.com/ zh_CN / 2.1 / ref / forms / fields /#initial


Let's say I have a Django form with ChoiceField:

class MyForm(forms.Form):
    name = forms.CharField(label="Name", required=True)
    some_object = forms.ChoiceField(label="Object", choices=[(0, '-----')] + [(x.id, x.name) for x in Obj.objects.all()])

Choisefield is being initialized with list of objects headed by 'empty choice'. There is no object with pk=0. In that form I have a clean() method:

def clean(self):
    if not Obj.objects.filter(self.cleaned.data['some_object'].exists():
        self.errors.update({'some_object': ['Invalid choice']})

It works well when I'm sending a form to a server, if data in it doesn't match conditions, field.is_valid returns False and I render form with error messages. But, when I create an empty form like this:

if request.method == 'GET':
    data = {'name': 'Untitled',
            'some_object': 0}
    form = MyForm(data)
    return render(request, 'app\template.html', {'form': form})

Django renders form with error message ('Invalid choice') even though form was just created and 'Object' select was intended to be set in empty position. Is it possible to disable form clean() method in specific cases? Or maybe I'm doing this all wrong? What is the best practice to create an empty form?

解决方案

The problem is that a form with any data dictionary passed to it counts as a "bound" form, against which Django will perform data validation. See here for details: https://docs.djangoproject.com/en/2.1/ref/forms/api/#bound-and-unbound-forms

You want an "unbound" form - to have default initial values in here, just set the initial property on your form fields. See full details here: https://docs.djangoproject.com/en/2.1/ref/forms/fields/#initial

这篇关于Django:表单创建时的表单验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆