如何在同一模板中呈现来自不同应用程序的视图?

时间:2019-01-29 17:37:56

标签: python django

我有两个应用程序(博客和类别)。在帖子列表模板上,我想获取类别博客名称和描述。

我尝试将导入类别模型放入博客视图,但未显示任何内容。因此,我已经制作了两个视图来渲染相同的模板,但是它不起作用。

博客模型:

from django.db import models
from django.utils import timezone
from autoslug import AutoSlugField
from category.models import Category


class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE,
    default = '')
    title = models.CharField(max_length=200)
    ...

class Meta:
    verbose_name = "Post"
    verbose_name_plural = "Posts"
    ordering = ['created_date']


def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return self.title

类别模型:

class Category(models.Model):
name = models.CharField(max_length=200)
slug = AutoSlugField(populate_from='name', default='')
parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE)
description = models.TextField(max_length=200)

class Meta:
    unique_together = ('slug', 'parent',)    # Enforcing that there can not be two
    verbose_name_plural = "categories"       # categories under a parent with same
                                             # slug

def __str__(self):                           # __str__ method elaborated later in
    full_path = [self.name]                  # post.  use __unicode__ in place of
                                             # __str__ if you are using python 2
    k = self.parent

    while k is not None:
        full_path.append(k.name)
        k = k.parent

    return ' -> '.join(full_path[::-1])

博客视图:

def post_list(request):
posts = Post.objects.all()
cat_blog = Category.objects.get(pk=1)
context = {
    'posts': posts,
    'cat_blog': cat_blog
}
return render(request, 'blog/post_list.html', context)

类别视图:

def cat_blog(request):
   cat_blog = Category.objects.get(pk=1)
   return render(request, 'blog/post_list.html', {'cat_blog': cat_blog})

post_list.html:

<div class="section-header text-center">
    {% for category in cat_blog %}
        <h1>{{ category.name }}</h1>
        <p class="tag">{{ category.description }}</p>
    {% endfor %}
</div>
<div class="row py-5">

{% for post in posts %}
    // This part is fine
{% endfor%}

发布循环很好。我如何在节标题中获得类别名称和描述?

1 个答案:

答案 0 :(得分:1)

一个URL给出一个视图,给出一个模板。

您使用“视图”为要渲染的模板提供上下文。

def post_list(request):
    posts = Post.objects.all()
    cat_blog = Category.objects.get(pk=1)
    context = {
        'posts': posts,
        'cat_blog': cat_blog
    }
    return render(request, 'blog/post_list.html', context)

您的url.py文件应指向post_list视图。