[Answered ]-Django: customize inline formset for 'through' model with multiple foreign keys

2👍

Here’s what I ended up doing. I didn’t use inlineformset_factory, because I couldn’t get the control I needed with inline formsets. For foods, I specified a custom ModelMultipleChoiceField with a CheckboxSelectMultiple widget, then did the same thing for each day by getting the days and looping through them.

class PlanForm(ModelForm):
    foods = forms.ModelMultipleChoiceField(
        queryset=Food.objects.all(), 
        required=False, 
        widget=forms.CheckboxSelectMultiple,
        label = "Foods:")

    def __init__(self, *args, **kwargs):
        super(PlanForm, self).__init__(*args, **kwargs)
        days = Day.objects.all()
        for day in days:        
            self.fields[day.name] = forms.ModelMultipleChoiceField(
                queryset=Meal.objects.all(), 
                required=False, 
                widget=forms.CheckboxSelectMultiple,
                label = day.name)

    class Meta:
        model = Plan
        fields = (['name','description','foods']+[day.name for day in Day.objects.all()])

This was the basic code to get the form that I wanted. Then, in your template, you could do something like this, and add your custom html:

{% for field in form %}
    {{ field.label_tag }}
    {% for choice in field %}
        {{choice}}
    {% endfor %}
{% endfor %}

I also ended up using this solution: http://schinckel.net/2013/06/14/django-fieldsets/ to get fieldsets, so I could do different rendering for each group on the form.

Leave a comment