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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With