Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access fields of a foreign key of a form in a template

Tags:

django

I am having trouble displaying the value of a field in a form in a template. The value should be available to the template, but it does not appear to be.

Here is the situation:

models.py:

class Member(models.Model):
    ...
    name = models.CharField(max_length=10, unique=True)
    description = models.CharField(max_length=50, blank=True)

class Pool(models.Model):
    ...
    members = models.ManyToManyField(Member, through='MemberPoolDates')

class MemberPoolDates(models.Model):
    member = models.ForeignKey(Member)
    pool = models.ForeignKey(Pool)
    date = models.DateField(null=True, blank=True)

views.py:

    pool = Pool.objects.get(id=pool_id)
    MemberFormSet = modelformset_factory(MemberPoolDates, form=MemberForm)
    memberformset = MemberFormSet(queryset=MemberPoolDates.objects.filter(
                                                                      pool=pool))

template:

<form action="" method="post">
{% csrf_token %}
<table>
{{ poolform }}
</table>
<h2>Pool entries:</h2>
{{ memberformset.management_form }}
{% for memberform in memberformset %}
    {{ memberform.id }}
    {{ memberform.member }} 
    {{ memberform.member.name }}
    {{ memberform.member.description }}
{% endfor %}
<input type="submit" name="save" value="Save pool"/>
</form>

In the template {{ memberform.member }} correctly displays a drop-down, but {{ memberform.member.description }} displays nothing and {{ memberform.member.name }} displays "member" instead of the value of member.name as text (what I wanted).

How can I access the fields of member in the template? More specifically, how can I display the value of member.name and member.description in my template through memberform?

like image 570
John Peters Avatar asked Aug 21 '12 08:08

John Peters


1 Answers

You could try this in your template (accessing the modelinstance of the form):

{{ memberformset.management_form }}
{% for form in memberformset %}
    {{ form.instance.member.name }}
    {{ form.instance.member.description }}
{% endfor %}

This should output the desired fields as plain text.

like image 167
Jingo Avatar answered Oct 08 '22 20:10

Jingo