Override the Django form form deletion behavior: delete the form instance if there is an empty field in the Django form set

I often come across this:

I want to hide the default delete field in the form sets and delete the instance of the object if a specific field is cleared in each form of the form set.

A typical problem is that either validation interferes or it violates the detection of an empty form and begins to add all forms (even empty additional ones) when a set of forms is saved.

+4
source share
2 answers

Here is the solution I found:

This code creates a model set of models, provides its verification, allowing an empty field, and then in the save mode determines which objects to delete and which forms to save.

TaskFormset = inlineformset_factory(User, FAQ, extra=3, can_delete=False, exclude=('user', 'answer',)) formset = TaskFormset(request.POST, request.FILES, instance=user) for form in formset: form.fields['question'].required = False // later when performing the formset save for form in formset: if form.instance.pk and form.cleaned_data['question'].strip() == '': form.instance.delete() elif form.cleaned_data: form.save() 
+4
source

There is a BaseFormSet method called _should_delete_form that makes it easy to automatically delete an instance based on your own criteria, but the private method is not so sure about future support. You also need to save the forms by calling formset.save() .

In the example below, it will delete the row if all fields values ​​are evaluated as false values.

 class MyFormSet(forms.BaseInlineFormSet): def _should_delete_form(self, form): """Return whether or not the form should be deleted.""" if form.cleaned_data.get(forms.formsets.DELETION_FIELD_NAME): return True # marked for delete fields = ('name', 'question', 'amount', 'measure', 'comment') if not any(form.cleaned_data[i] for i in fields): return True return False 
0
source

Source: https://habr.com/ru/post/1488139/


All Articles