[Answered ]-Django modelformset_factory is adding a bogus 'id' field to my modelforms, and I'd like it to stop


Use form.visible_fields instead.


            {% for form in formset %}
                {% for field in form.visible_fields %}
                    {{ field.label_tag }} {{ field }}
                {% endfor %}
            {% endfor %}


Here’s the solution I found, and I admit it isn’t entirely satisfactory:

class ExistingTemplateFormset(modelformset_factory(ArticlesTemplate, extra = 0, form=ExistingTemplateForm)):
    def __init__(self, *args, **kwargs):
        super(ExistingTemplateFormset, self).__init__(*args, **kwargs)
        for x in self: x.fields['id'].widget = forms.HiddenInput()

This is a solution that, to my surprise, didn’t work:

class ExistingTemplateForm(ModelForm):
    selected = forms.BooleanField(required=False, initial=False, row_renderer = default_renderer, widget=forms.RadioSelect(), label = 'use?')
    id = forms.ModelChoiceField(widget = forms.HiddenInput(), queryset = ArticlesTemplate.objects.all())
    class Meta:
        model =  ArticlesTemplate
        exclude = ('template_file', 'organisation_for', 'mime_type',)
## This __init__ has no effect on the widget used to render id
    def __init__(self, *args, **kwargs):
        super(ExistingTemplateForm, self).__init__(*args, **kwargs)
        self.fields['id'] = forms.ModelChoiceField(widget = forms.HiddenInput(), queryset = ArticlesTemplate.objects.all())
        self.fields['id'].widget = forms.HiddenInput()


I have no solution for exactly this problem which i have, too. But I have found a workaround:

I render the id-field without label an as hidden field with the tag {{form.id}}. The output is for example: <input id="id_form-0-id" name="form-0-id" type="hidden" value="1" />

But if you render the formset with tags like {{ formset }} or

{% for form in formset %}
{{ form }}
{% endfor %}

You will become a visible label before the id field.

I hope i could help

Leave a comment