django中的formset_factory验证

时间:2012-05-29 11:12:08

标签: django django-forms

如果没有给出输入,如何在NicheSkills表格的第一个字段中设置验证,我点击保存按钮。我想在第一行没有给出输入时将错误显示为“此字段是必需的”。请帮助我。

Models.py:

class NicheSkills(Audit):
    user                    = models.ForeignKey(User, null = True, blank = True)      
    title                   = models.CharField(max_length = 15)    
    special_skill           = models.CharField(max_length = 15)

Forms.py:

class NicheSkillsForm(forms.Form):
    title                   = fields.CharField(max_length=150)
    special_skill           = fields.CharField(max_length=150)

NicheFormset = formsets.formset_factory(NicheSkillsForm, extra = 1)  

模板:

<table cellpadding="3" cellspacing="3" border="0" style="margin-left:65px;">
                        <tbody>
                            <tr><td>{{ form5.current_role }}</td></tr>
                            <tr><td><span class = "forget-errors">{{ form5.current_role.errors }}</span></td></tr>
                            <tr><td align="center"><input type="button"   id="form5" name="save" value="Save" onclick = "save_form(this.id)" /></td></tr>
                        </tbody>
</table>

Views.Py

NicheFormset = formsets.formset_factory(NicheSkillsForm, extra = 0)
if request.method == "POST":
    formset6 = NicheFormset(request.POST, prefix='fs6')
    if formset6.is_valid():
        for values in formset6.cleaned_data:
            niche_details = NicheSkills(
                                    title          = values['title'],
                                    special_skill     = values['special_skill'])

            niche_details.save()  
else:
    NicheFormset = formsets.formset_factory(NicheSkillsForm, extra = 1)
    formset6 = NicheFormset(prefix='fs6')        
return render_to_response('test.html', locals(), RequestContext(request))   

1 个答案:

答案 0 :(得分:0)

使用Django Forms validation,为您的表单类定义clean()方法并验证其中的字段。

如果要显示整个表单的错误 - 只需使用正确的错误说明引发ValidationError

如果要显示与字段相关的错误(例如,连接到第一个空白字段),则必须修改self._errors[field]

所有这些都在文档的链接部分中描述。使用self._errors的示例位于最后一个代码段中。