表单集上的 Django 自定义验证
我正在寻找一些有关如何对表单集进行自定义验证的建议。
这就是我现在所拥有的,它返回以下错误,我不完全知道如何处理。
Exception Value:
'MilestoneFormFormSet' object has no attribute 'save'
Forms.py
class BaseMilestoneFormSet(BaseFormSet):
def clean(self):
for form in self.forms:
data = form.cleaned_data
target_date = data["target_date"]
project = data["project"]
if target_date > project.target_date:
raise forms.ValidationError("Target Date is outside of project target date")
return data
MilestoneFormSetNew = modelformset_factory(Milestone, formset=BaseMilestoneFormSet, max_num=50, extra=1)
Views.py 摘录
if request.method == 'POST': # Loop through the submitted formsets check for erros and save the data.
formsetNew = MilestoneFormSetNew(request.POST, prefix='new')
if formsetNew.is_valid():
formsetNew.save()
return HttpResponseRedirect(reverse('pooflinger.project.views.detail', args=(project.id,)))
I am looking for some advice on how to do custom validation on formsets.
This is what I have right now and it returns the following error that I do not entirely know how to deal with.
Exception Value:
'MilestoneFormFormSet' object has no attribute 'save'
Forms.py
class BaseMilestoneFormSet(BaseFormSet):
def clean(self):
for form in self.forms:
data = form.cleaned_data
target_date = data["target_date"]
project = data["project"]
if target_date > project.target_date:
raise forms.ValidationError("Target Date is outside of project target date")
return data
MilestoneFormSetNew = modelformset_factory(Milestone, formset=BaseMilestoneFormSet, max_num=50, extra=1)
Views.py excerpt
if request.method == 'POST': # Loop through the submitted formsets check for erros and save the data.
formsetNew = MilestoneFormSetNew(request.POST, prefix='new')
if formsetNew.is_valid():
formsetNew.save()
return HttpResponseRedirect(reverse('pooflinger.project.views.detail', args=(project.id,)))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的 clean 方法中有一个缩进错误 - 返回应该在 for 循环之外。
但不要在表单集中进行这种类型的验证。当您在表单集中跨表单进行验证时,表单集验证非常有用。您正在比较每个表单中的值,因此对表单集使用自定义 ModelForm 更有意义。
You have an indentation error in your clean method - the return should be outside the for loop.
But don't do this type of validation in the formset. Formset validation is useful when you are validating across forms in the formset. You are comparing values within each form, so it makes more sense to use a custom ModelForm for the formset.