Reputation: 4452
I want to know how it is possible to display many-to-many relations in the django template. I posted my views.py and my models.py. I tried to find the solution by myself but I didn't really understand how to solve the problem :/
models.py
class topic(models.Model):
topic = models.TextField(verbose_name = 'Thema')
learningObjectivesTopic = models.ManyToManyField(learningObjective, verbose_name = "Lernziel")
class learningObjective(models.Model):
learningObjectives = models.TextField(verbose_name = 'Lernziel')
views.py
@login_required(login_url='login')
def themen(request):
return render(request, 'themen.html')
@login_required(login_url='login')
def create_themen(request):
neueThemen=topic(topic=request.POST['thema'])
neueThemen.save()
neueThemen_Lernziel=learningObjective(learningObjectives=request.POST['Lernziel'])
neueThemen_Lernziel.save()
neueThemen.learningObjectivesTopic.add(neueThemen_Lernziel)
return render(request, 'themen.html', {'thema': topic.objects.all(), 'lernziel': learningObjective.objects.all()})
and my unfinished template "themen.html"
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="{% url 'create_themen' %}" method="post">
{% csrf_token %}
<br>Hallo Benutzer: {{ user.username }}</br>
<br>Thema: <textarea name="thema" rows="3" cols="45"></textarea></br>
<br>Lernziel: <textarea name="Lernziel" rows="3" cols="45"></textarea></br>
<input type="submit" value="Absenden" />
<br>Aktuelle Themen:</br>
</form>
{% for thema_ in thema %}
{{ thema_.topic }}<br/>
{{ thema_.
{% endfor %}
</body>
</html>
Upvotes: 0
Views: 2523
Reputation: 99640
Given the thema
object, if you want to display the many to many fields,
{% for topic in thema %}
{{topic.topic}}
{% for lo in topic.learningObjectivesTopic.all %}
{{lo.learningObjectivesTopic}}
{% endfor %}
{% endfor %}
Upvotes: 1