Python 如何在同一模板中呈现来自不同应用程序的视图?
我有两个应用程序(博客和分类)。在帖子列表模板上,我想获得类别博客的名称和描述 我曾尝试将导入类别模型放在博客视图中,但没有显示任何内容。因此,我制作了两个视图来呈现相同的模板,但它不起作用 博客模式:Python 如何在同一模板中呈现来自不同应用程序的视图?,python,django,Python,Django,我有两个应用程序(博客和分类)。在帖子列表模板上,我想获得类别博客的名称和描述 我曾尝试将导入类别模型放在博客视图中,但没有显示任何内容。因此,我制作了两个视图来呈现相同的模板,但它不起作用 博客模式: from django.db import models from django.utils import timezone from autoslug import AutoSlugField from category.models import Category class Post(
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:
{cat_blog%中类别的%s}
{{category.name}
{{category.description}
{%endfor%}
{posts%%中的post为%s}
//这部分很好
{%endfor%}
post循环很好。如何才能在我的分区标题中获取类别名称和描述?一个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_列表视图。同一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)