django - 如何在“base.html”中显示模型中的列表对象并将其扩展到所有其他模板

DAM*_*225 1 python django

我在“base.html”中有一个导航栏,我想在其上列出模型中的对象,因此该列表在扩展“base.html”的所有其他模板上都可见

'base.html'

<nav>
   {% for category in categories %}
      <a href="#">{{ category.category_name }}</a>
   {% endfor %}
</nav>
Run Code Online (Sandbox Code Playgroud)

模型.py

class Categories(models.Model):
   category_name           = models.CharField(max_length=100, null=True)
Run Code Online (Sandbox Code Playgroud)

视图.py

class NavbarView(ListView):
   model               = Categories
   template_name       = 'base.html'
   context_object_name = 'categories'
Run Code Online (Sandbox Code Playgroud)

urls.py

path('nav/', views.NavbarView.as_view(), name='nav')
Run Code Online (Sandbox Code Playgroud)

这使得类别列表仅在“nav/”网址上可见,但在扩展“base.html”的所有模板中不可见

我怎样才能做到这一点 ?谢谢

arj*_*jun 6

您可以为此使用上下文处理器。例如,如果您希望类别在所有模板中都是动态的:

上下文处理器.py

def categories(request):
    categories = Categories.objects.all()
    return {"categories": categories}
Run Code Online (Sandbox Code Playgroud)

并将此 context_processor 添加到您的 settings.py 文件中

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                ......................,
                'your_app.context_processors.categories', # path to your context_processor
            ],
Run Code Online (Sandbox Code Playgroud)