Django Formset错误与输入名称 [英] Django Formset Errors With Input Name
问题描述
我想获得与其输入名称相对应的表单错误。在这里,我使用ajax发送表单数据。
models.py
class Category(models.Model):
category = models.CharField(max_length = 128)
forms.py
class CategoryForm(forms.ModelForm):
pre>
class Meta:
model = Category
field =__ all__
CategoryFormset = modelformset_factory(Category,CategoryForm,,min_num = 2,extra = 0)
当我提交表单时,我收到这样的错误
python shell
formset.errors
[{'category':[你需要这个字段']},{'category':[ ']}]
但在我的模板输入名称是不同的
form-0-category
和form-1-category
。所以有可能得到类似的错误:
[{'form-0-category':[你需要这个字段']},{'form-1-category ':你需要这个字段']}]
。
有人请帮助我。
模板
; p为H.
< input id =id_form-0-categorymaxlength =128name =form-0-categorytype =text/>
< / p>
< p>
< input id =id_form-1-categorymaxlength =128name =form-1-categorytype =text/>
< / p>
解决方案Django不提供错误列表你可以自己生成这个格式:
prefixed_errors = [{'%s-%s-%s'% (formset.prefix,index,k):v for k,v in errors.items()}
for(index,errors)in枚举(formset.errors)]
这会在您的问题中生成一个字典列表。我想你可能需要一个单一的字典,你可以使用它:
errors_dict = {'%s-%s-% s'%(formset.prefix,index,k):v for(index,errors)in enumerate(formset.errors)for k,v in errors.items()}
/ pre>
I want to get formset errors corresponding to its input name. Here I am using ajax to send the form data.
models.py
class Category(models.Model): category = models.CharField(max_length=128)
forms.py
class CategoryForm(forms.ModelForm): class Meta: model=Category field ="__all__" CategoryFormset = modelformset_factory(Category, CategoryForm, , min_num=2, extra=0)
when i submit the form, i got the errors like this
python shell
formset.errors [{'category': [u'This field is required.']}, {'category': [u'This field is required.']}]
But in my templates input name is different
form-0-category
andform-1-category
. So is it possible to get errors something like this:[{'form-0-category': [u'This field is required.']}, {'form-1-category': [u'This field is required.']}]
. Somebody please help me.templates
<p> <input id="id_form-0-category" maxlength="128" name="form-0-category" type="text"/> </p> <p> <input id="id_form-1-category" maxlength="128" name="form-1-category" type="text" /> </p>
解决方案Django doesn't provide the list of errors in the format you want, but you can generate it yourself:
prefixed_errors = [{'%s-%s-%s' % (formset.prefix, index, k): v for k,v in errors.items()} for (index, errors) in enumerate(formset.errors)]
This generates a list of dictionaries as in your question. I think you might want a single dictionary, which you could get with:
errors_dict = {'%s-%s-%s' % (formset.prefix, index, k): v for (index, errors) in enumerate(formset.errors) for k,v in errors.items()}
这篇关于Django Formset错误与输入名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!