Python – How to loop over form field choices and display associated model instance fields

djangodjango-formsdjango-modelsdjango-templatespython

I have a ModelForm with a multiple choice field. The choices are populated instances of Hikers belonging to a specific Club.

I want to customize the way my form displays, by displaying the choices in a table where the 1st column contains checkboxes, and a few more columns display the details of each hiker. So for example the columns are (checboxes, name, age, favourite hiking trail).

I'm not sure how to approach this. How do I access and display the form field choices with it's associated model instance fields in my template. Anybody know of the Django way to do this?

#models.py
class Club(models.Model):
    title = models.CharField()
    hikers = models.ManyToManyField(Hikers)

class Hiker(models.Model):
    name = models.CharField()
    age = models.PositiveIntegerField()
    favourite_trail = models.CharField()

#forms.py
class ClubForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        club_pk = kwargs['club_pk']
        del kwargs['club_pk']
        super(ClubForm, self).__init__(*args, **kwargs)
        choices = [(ts.pk, ts.name) for hiker in Club.objects.filter(pk=club_pk)]
        self.fields['hikers'].choices = choices

    class Meta:
        model = Club
        fields = ('hikers',)
        widgets = {'hikers': forms.CheckboxSelectMultiple}

Best Answer

Easiest would be if you define the whole form in a HTML template. You should be able to iterate over a field's values in a template like that:

{% for value, text in form.hikers.field.choices %}
    {{ value }}: {{ text }}
{% endfor %}
Related Topic