How to change widget type of DELETE field in django form set

I am using formet with can_delete = True. I want to change the DELETE field widget to hidden input. I can't seem to find a good way to do this. I tried:

Change the form widget to HiddenInput and / or add a hidden field to the form definition:

class MyForm(ModelForm): DELETE = forms.BooleanField(widget=forms.HiddenInput) class Meta: model = MyModel widgets = {'DELETE' : forms.HiddenInput} 

Do it with shape change

 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 this, it really changes the field to hidden, but it seems to be hacked (actually overwriting the usual add_fields method). How should you do this?

== EDIT ==

It turns out that using a hidden field is not so good with the shape framework anyway. You should definitely use the checkbox and hide it with css. If you want to edit the css of the checkbox in Django, I still think you need to change the add_fields method as above, and then you can change the css widget.

+7
source share
2 answers

This does not change anything if your input is of type = hidden, or if it is of type = checkbox and : none.

IMHO elegant style in CSS will look like this:

 td.delete input { display: none; } 

Or in JavaScript:

 $('td.delete input[type=checkbox]').hide() 

Or, in admin:

 django.jQuery('td.delete input[type=checkbox]').hide() 

This seems like a better direction because:

  • It will not change your JavaScript code and
  • This is one line of code against lots of Python hackers.
+10
source

The shortest code to accomplish what you need:

 class MyFormSet(BaseFormSet): def add_fields(self, form, index): super(MyFormSet, self).add_fields(form, index) form.fields[DELETION_FIELD_NAME].widget = forms.HiddenInput() 

This cannot be considered a hack because it is mentioned in Django's official docs:

https://docs.djangoproject.com/en/1.4/topics/forms/formsets/#adding-additional-fields-to-a-formset

Django sources for reading:

+21
source

All Articles