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


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?
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()
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 = [(, for hiker in Club.objects.filter(pk=club_pk)]
        self.fields['hikers'].choices = choices

    class Meta:
        model = Club
        fields = ('hikers',)
        widgets = {'hikers': forms.CheckboxSelectMultiple}
3/20/2013 7:44:03 PM

Accepted 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 %}
12/14/2010 1:51:52 PM

Try this solution :

{% for choice in form.my_choice_field.field.choices %}
    <input type="radio" name="my_choice_field" value="{{choice.0}}"
      {% ifequal choice.0 %} 
      {% endifequal %}/>
    <label for="">{{choice.1}}</label>
{% endfor %}

see this link :

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow