我想知道如何在django模板中显示多对多关系。我发布了我的views.py和我的models.py.我试图自己找到解决方案,但我真的不明白如何解决问题:/
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()})
和我未完成的模板“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>
答案 0 :(得分:1)
给定thema
对象,如果要显示多个到多个字段,
{% for topic in thema %}
{{topic.topic}}
{% for lo in topic.learningObjectivesTopic.all %}
{{lo.learningObjectivesTopic}}
{% endfor %}
{% endfor %}