简体   繁体   English

如何在模板中显示ManyToMany字段

[英]How to display a ManyToMany fields in the template

I wonder how I can retrieve my template a ManyToMany fields ... For example, in my model I would like to retrieve the page corresponding to each question and post it in the template ... I have 4 values in my class Page ("visit 1 visit 2 visit 3, 4 .. visit") And I associated in my database each question with a "visit" 我想知道如何在ManyToMany字段中检索我的模板...例如,在我的模型中,我想检索与每个问题相对应的页面并将其发布到模板中......我的班级页面中有4个值(“访问1访问2访问3,4 ..访问“)我在我的数据库中关联每个问题与”访问“

And I wish I could now see how visits to any question in my template. 我希望我现在可以看到如何访问我的模板中的任何问题。

I will share my models: 我将分享我的模特:

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)

And my templates : 我的模板:

{% 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 %}

How do I call in the template page for a given question? 如何在模板页面中调用给定问题?

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 %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM