[英]issue with django context processor
当模板内部的href重定向到详细信息时,上下文处理器不起作用
context_processor.py
from .models import Category def polls_category(request): for e in Category.objects.all(): name=e.title return {"polls_category":name}
settings.py中的Context_processor
'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'products.context_processors.polls_category' ], },
模板
{% for obj in gili_list %} <p><small><a href='{{obj.get_absolute_url}}'>{{polls_category}}</a></small></p> {% endfor %}
views.py
class CategoryListView(ListView): model = Category template_name = "products/product_list.html" def get_context_data(self, *args, **kwargs): context = super(CategoryListView, self).get_context_data(*args, **kwargs) context['gili_list'] = Category.objects.all() return context
models.py
class Category(models.Model): title = models.CharField(max_length=120, unique=True) slug = models.SlugField(unique=True) description = models.TextField(null=True, blank=True) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
首先,在views.py中更改视图以删除get_context_data方法,如果您使用上下文处理器将上下文放入导航栏中,则不需要此额外的上下文。 然后添加如下所示的详细视图(我假设您的详细信息模板将被称为“ product_detail.html”)。 如果尚未导入,则需要导入“ DetailView”:
views.py
from django.views.generic import ListView, DetailView
class CategoryListView(ListView):
model = Category
template_name = "products/product_list.html"
class CategoryDetailView(DetailView):
template_name = 'products/product_detail.html'
model = Category
context_object_name = 'category'
其次,更改模板,删除“ gili_list”并替换为“ polls_catagory”,这是来自您的context_processors.py的上下文,如下所示:
product_list.html
{% for obj in polls_category %}
<p><small><a href='{{obj.get_absolute_url}}'>{{ obj.title }}</a></small></p>
{% endfor %}
第三,使用“ get_absolute_url”方法修改您的models.py。 我还添加了一个' str '方法,以使其在Django admin中看起来更好。 确保您导入“反向”:
models.py
from django.db import models
from django.urls import reverse
class Category(models.Model):
title = models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique=True)
description = models.TextField(null=True, blank=True)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
def get_absolute_url(self):
return reverse('category_detail', kwargs={'slug': self.slug})
def __str__(self):
return f'{self.title}'
第四:您的上下文处理器现在正在做某事,它向每个页面,因此向您的导航栏提供polls_category:
context_processors.py
def polls_category(request):
polls_category = Category.objects.all()
return {"polls_category": polls_category}
第五,在详细信息模板中,添加此内容以检查上下文是否通过:
product_detail.html
{{ category.title }} <br>
{{ category.active }}
在我看来,这一切都工作得很好。 通过url中的子弹加上“ Django magic”,可以在product_detail.html中获取正确的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.