Home > OS >  Prevent Django to save an specific form from a formset
Prevent Django to save an specific form from a formset

Time:10-17

I'm working with a Django formset and I'm trying to prevent certain forms that could be partially filled to be saved.

Form:

class WeeksForm(forms.ModelForm):
    monday = forms.DecimalField(required=False)
    tuesday = forms.DecimalField(required=False)
    wednesday = forms.DecimalField(required=False)
    thursday = forms.DecimalField(required=False)
    friday = forms.DecimalField(required=False)
    saturday = forms.DecimalField(required=False)
    sunday = forms.DecimalField(required=False)

    class Meta:
        model = Weeks
        fields = ('activity', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday')

Formset:

WeeksFormset = modelformset_factory(Weeks, form=WeeksForm, extra=10, can_delete=True)

I'm dynamically generating the forms using JS and it automatically fills the field 'activity' but the problem is that sometimes the user might decide to not complete the other fields (those named with weekdays, "monday", "tuesday", etc...). If that is the case I end up with an "empty" form (not really empty because the field "activity" was filled) that I'm not interested in saving.

I'm trying to somehow prevent in my view that these forms are saved:

views.py

if request.method == 'POST':
        formset = WeeksFormset(request.POST)
        if formset.is_valid():
            for form in formset.forms:
                # From here is pseudocode, I want that if a form has all the weekdays empty that form is not saved
                if form.instance.monday and form.instance.tuesday and ... form.instance.sunday == None:
                    form.delete()
                # End of pseudocode, this approach didn't work

                form.instance.user = request.user 
            formset.save()
            return HttpResponseRedirect(reverse("time")

I'm really struggling with this, I have tried several approaches without success.

CodePudding user response:

Just save the forms that match:

if request.method == 'POST':
    formset = WeeksFormset(request.POST)
    if formset.is_valid():
        for form in formset.forms:
            instance = form.instance
            if any(
                f is not None
                for f in [
                    instance.monday,
                    instance.tuesday,
                    instance.wednesday,
                    instance.thursday,
                    instance.friday,
                    instance.saturday,
                    instance.sunday,
                ]
            ):
                instance.user = request.user
                form.save()
        # do *not* save the formset
        return redirect('time')
  • Related