gpt4 book ai didi

python - 如何在模板中显示ManyToMany字段

转载 作者:行者123 更新时间:2023-11-30 23:00:25 24 4
gpt4 key购买 nike

我想知道如何在 ManyToMany 字段中检索我的模板...例如,在我的模型中,我想检索与每个问题对应的页面并将其发布到模板中......我的类(class)页面中有 4 个值(“访问 1 访问 2 访问 3, 4 .. 访问”)我在数据库中将每个问题与“访问”相关联

我希望现在可以看到如何访问我的模板中的任何问题。

我将分享我的模型:

class Page(models.Model):
title = models.CharField(max_length=30)


def __str__(self):
return self.title

class Question(models.Model):
label = models.CharField(max_length=30)
page = models.ManyToManyField(Page)

def __str__(self):
return self.label

class Reply(models.Model):
question = models.ForeignKey(Question)
user = models.ForeignKey(Personne)
answer = models.CharField(max_length=30)
creationDate = models.DateTimeField(default=datetime.datetime(2016, 1, 20, 15, 4, 21, 467165))

def __str__(self):
return str(self.answer)

还有我的模板:

{% for reply in replies %}<br>
<br> {{ reply.user }}
{{ reply.question }} -
{{ reply.answer }}
(dans la :{% for page in questions.page %} {{ page }}) {% endfor %} #this is this line who doesn't work
{% endfor %}

如何调用给定问题的模板页面?

EDIT :

def reply(request):
replies = Reply.objects.all()
questions = Question.objects.all()
logged_user = get_logged_user_from_request(request)
pages = Page.objects.all()
form = ReplyBisForm(request.GET)
personnes = Personne.objects.all()
if logged_user:
if len(request.GET) > 0:
form = ReplyBisForm(request.GET)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/reply')
else:
return render_to_response('polls/reply.html', {'personnes': personnes, 'replies': replies, 'questions': questions,'pages':pages, 'form': form})
else:
form = ReplyBisForm()
return render_to_response('polls/reply.html', {'personnes':personnes, 'replies': replies, 'questions': questions, 'pages':pages, 'form': form})
else:
return HttpResponseRedirect('/login')

最佳答案

由于 ManyToMany 字段转换为 RelatedManager对于每个模型实例,您应该指定相关对象的子集,或者直接使用 all() :

(dans la :{% for page in reply.question.page.all %} {{ page }}) {% endfor %}

关于python - 如何在模板中显示ManyToMany字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35288084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com