访问Django模板中的“多对多"字段 [英] Access Many-to-Many field within Django template

查看:35
本文介绍了访问Django模板中的“多对多"字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下博客项目:

models.py:

models.py:

django.db导入模型中的

from django.db import models
from django.utils import timezone

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    pub_date = models.DateTimeField(default=timezone.now)
    categories = models.ManyToManyField('Category')

    def __str__(self):
        return self.title

class Category(models.Model):
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

    # Change the name in Admin from categorys to categories
    class Meta:
        verbose_name_plural = "categories"

views.py:

views.py:

来自django.shortcuts的

from django.shortcuts import render
from .models import Post, Category, Comment

def getPosts(request):

    posting = Post.objects.all().order_by('-pub_date')
    categories = Category.objects.all()

    context = {
        'posting':posting,
        'categories':categories,
              }
    return render(request, 'posts/getPosts.html', context)

getPosts.html模板:

getPosts.html template :

    {% if posting %}
        {% for article in posting %}
            <h3>{{article.title}}</h3>
            <ul>{{article.body}}</ul>
            <ul>Posted : {{article.pub_date}}</ul>

            <ul>
                <em>Found in category : </em>

                {{ article.categories }} 
                {{ article.categories.all }}
                {% for category in categories %}
                    {{category.title}} 
                {% endfor %} 
            </ul>
        {% endfor %}
    {% endif %}

我有3条帖子,都可以正确显示,但是

I have three posts, which all display properly, but

{{article.categories}}在给我:

{{article.categories}} is giving me:

posts.Category.None

{{article.categories.all}}给了我

{{article.categories.all}} gives me

QuerySet [<Category: Diving>]

第二个循环输出所有类别的列表,我希望这只是一次测试运行:

And the second loop outputs the list of all categories, which I expected as just a test run:

Kit & Packing Diving Places Tips Private

我试图简单地查看每个帖子的类别名称,该类别名称已在管理面板中选择并通过管理面板保存.

I am trying to simply pull through the category name for each post, which has been selected in the admin panel and saved through the admin panel.

我尝试了上千种不同的建议,例如将视图更改为category = post.category_set.all(),并且已经对此进行了数天的研究,但无处可寻.

I have tried what feels like a thousand different suggestions, such as changing the view to category = post.category_set.all(), and have been researching this for days now, but am getting no-where.

推荐答案

您已经有了正确的答案; article.categories.all ,您应该对其进行循环.

You already have the right answer; article.categories.all, which you should loop over.

{% for category in article.categories.all %}
    {{category.title}} 
{% endfor %} 

视图中根本不需要 categories 值.

这篇关于访问Django模板中的“多对多"字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆