Python 为什么我能';t在Django中将类别传递给我的模板
我在模板目录下的分区中有一个header.html文件。我有一个类别的部分,我需要从数据库中获取。因此,我在我的应用程序文件夹中创建了一个自定义templatetag。我已经为最新的下拉文章和类别写了标签。好吧,不知何故,文章是从数据库中提取出来的,但类别不是 型号.pyPython 为什么我能';t在Django中将类别传递给我的模板,python,django,Python,Django,我在模板目录下的分区中有一个header.html文件。我有一个类别的部分,我需要从数据库中获取。因此,我在我的应用程序文件夹中创建了一个自定义templatetag。我已经为最新的下拉文章和类别写了标签。好吧,不知何故,文章是从数据库中提取出来的,但类别不是 型号.py from django.db import models from django.utils.text import slugify from django.urls import reverse from ckeditor_
from django.db import models
from django.utils.text import slugify
from django.urls import reverse
from ckeditor_uploader.fields import RichTextUploadingField
from datetime import datetime
class Category(models.Model):
label = models.CharField(max_length=15, unique=True)
def __str__(self):
return self.label
class Article(models.Model):
title = models.CharField(max_length=80, unique=True, help_text='Max Length: 80')
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
banner_image = models.ImageField(upload_to='photos/%Y/%m/%d/', help_text='Banner Image', default=None)
description = models.TextField(max_length=200 ,help_text='Short descirption about the post')
content = RichTextUploadingField(help_text='Site Content')
published = models.BooleanField(default=True)
date_created = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
views = models.BigIntegerField(default=0)
featured = models.BooleanField(default=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('article', kwargs={'category': self.category, 'post': self.title})
我的自定义临时标签
from django import template
from articles.models import Article, Category
register = template.Library()
@register.inclusion_tag('partials/_header.html')
def recent():
category = Category.objects.all() #not being fetched
recents = Article.objects.filter(published=True).order_by('-date_created')[:9]
trendings = Article.objects.filter(published=True).order_by('-views')[:9]
return {
'recents': recents,
'trendings': trendings,
'category': category,
}
**my header.html文件**
<div id="asmCategoryContents" class="asm-Category_Contents">
{% for cat in category %}
<a href=""> {{ cat }}</a>
{% empty %}
<h2>Not found</h2>
{% endfor %}
</div>
{%类别中的cat为%}
{%empty%}
找不到
{%endfor%}
我使用MYSQL作为我的数据库。
我已经运行了所有迁移,并为类别创建了标签,但是,它总是为类别显示Not found。但是,对于文章来说,它工作得很好。实际上,您不需要模板标记。相反,您需要一个自定义模板。你可以这样写:
# filename your_app/context_processors/recent.py
from articles.models import Article, Category
def recent(request):
category = Category.objects.all() #not being fetched
recents = Article.objects.filter(published=True).order_by('-date_created')[:9]
trendings = Article.objects.filter(published=True).order_by('-views')[:9]
return {
'recents': recents,
'trendings': trendings,
'category': category,
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['./templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# rest of the context processors
'your_app.context_processors.recent',
],
}
}
]
然后将其添加到context\u处理器
,如下所示:
# filename your_app/context_processors/recent.py
from articles.models import Article, Category
def recent(request):
category = Category.objects.all() #not being fetched
recents = Article.objects.filter(published=True).order_by('-date_created')[:9]
trendings = Article.objects.filter(published=True).order_by('-views')[:9]
return {
'recents': recents,
'trendings': trendings,
'category': category,
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['./templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# rest of the context processors
'your_app.context_processors.recent',
],
}
}
]
模板=[
{
'BACKEND':'django.template.backends.django.DjangoTemplates',
'DIRS':['/模板'],
“应用程序目录”:正确,
“选项”:{
“上下文处理器”:[
#其余的上下文处理器
'您的应用程序上下文处理器最近',
],
}
}
]
为什么不将Queryset作为上下文数据传递?因为我不想为header.html文件使用单独的视图函数。我在这个网站上看到了一个答案,使用自定义模板标签将是这个目的的最佳选择,因此。。。