Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

#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}
like image 753
sizeight Avatar asked Dec 14 '10 08:12

sizeight


2 Answers

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 %}
like image 111
Bernhard Vallant Avatar answered Nov 10 '22 15:11

Bernhard Vallant


Try this solution :

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

see this link : http://www.ilian.io/django-forms-choicefield-and-custom-html-output/

like image 13
Armance Avatar answered Nov 10 '22 17:11

Armance