简体   繁体   中英

Access Many-to-Many field within Django template

I have the following blog project :

models.py:

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:

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

I have three posts, which all display properly, but

{{article.categories}} is giving me:

posts.Category.None

{{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.

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.

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

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

You don't need the categories value in the view at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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