开发者

Django custom validation on formsets

开发者 https://www.devze.com 2023-01-23 09:10 出处:网络
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.

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):
        fo开发者_开发知识库r 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,)))


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.

class MilestoneForm(forms.ModelForm):

    def clean(self):
        data = self.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, form=MilestoneForm, max_num=50, extra=1)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号