I'm using a formset with can_delete=True. I want to change the widget of the DELETE field to a hidden input. I can't seem to find a good way to do this. What I've tried is:
Change the form's widget to HiddenInput and/or add a hidden field in the form definition:
class MyForm(ModelForm):
DELETE = forms.BooleanField(widget=forms.HiddenInput)
class Meta:
model = MyModel
widgets = {'DELETE' : forms.HiddenInput}
Do the above with a change in the formset
class MyFormSet(BaseModelFormSet):
def add_fields(self, form, index):
originalDeletion = None
if DELETION_FIELD_NAME in form.fields:
originalDeletion = form.fields[DELETION_FIELD_NAME]
super(MyFormSet, self).add_fields(form,index)
if originalDeletion is not None:
form.fields[DELETION_FIELD_NAME] = originalDeletion
If I do these both it does actually change the field to hidden but this seems like a bit of a hack (effectively overwriting the usual add_fields method). How are you supposed to do this?
== EDIT ==
It turns out that using a hidden field is not so good with the form framework anyway. You should definitely use a checkbox and hide it with css. If you want to do adjust the css of the checkbox in Django I still think you have to change the add_fields method as above, which then allows you to change the widget's css.
Django formset allows you to edit a collection of the same forms on the same page. It basically allows you to bulk edit a collection of objects at the same time.
Validating the number of forms in a formset. Django provides a couple ways to validate the minimum or maximum number of submitted forms. Applications which need more customizable validation of the number of forms should use custom formset validation.
Django model formsets provide a way to edit or create multiple model instances within a single form. Model Formsets are created by a factory method. The default factory method is modelformset_factory(). It wraps formset factory to model forms. We can also create inlineformset_factory() to edit related objects.
The shortest code to accomplish what you need is:
class MyFormSet(BaseFormSet):
def add_fields(self, form, index):
super(MyFormSet, self).add_fields(form, index)
form.fields[DELETION_FIELD_NAME].widget = forms.HiddenInput()
It cannot be considered a hack because it's mentioned in the official Django docs:
https://docs.djangoproject.com/en/1.4/topics/forms/formsets/#adding-additional-fields-to-a-formset
Django sources to read:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With