[英]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.