【问题标题】:django - how to display list objects from model in 'base.html' and extends it to all other templatesdjango - 如何在“base.html”中显示模型中的列表对象并将其扩展到所有其他模板
【发布时间】:2019-07-31 10:31:42
【问题描述】:

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

'base.html'

<nav>
   {% for category in categories %}
      <a href="#">{{ category.category_name }}</a>
   {% endfor %}
</nav>

models.py

class Categories(models.Model):
   category_name           = models.CharField(max_length=100, null=True)

views.py

class NavbarView(ListView):
   model               = Categories
   template_name       = 'base.html'
   context_object_name = 'categories'

urls.py

path('nav/', views.NavbarView.as_view(), name='nav')

这使得类别列表仅在 'nav/' url 上可见,而不是在扩展 'base.html 的所有模板中可见

我该怎么做?谢谢

【问题讨论】:

    标签: python django


    【解决方案1】:

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

    context_processors.py

    def categories(request):
        categories = Categories.objects.all()
        return {"categories": categories}
    

    并将这个 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
                ],
    

    【讨论】:

    • 我需要为这个视图添加 url 吗?
    • @Progam 不,你不需要。您只需要在设置中为您的自定义处理器提供路径。
    【解决方案2】:

    为您提供更多灵活性的一个选项是创建一个 mixin:

    class NavMixin(object):
        def get_context_data(self, **kwargs):
            context = super(NavMixin, self).get_context_data(**kwargs)
            context['categories'] = Categories.objects.all()
            return context
    

    您可以将它包含在您的基于类的视图中,如下所示:

    class MyListView(NavMixin, ListView):
        ...
    

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 2020-07-08
      • 2016-06-11
      • 2016-07-12
      • 1970-01-01
      • 2013-08-30
      • 2013-08-01
      • 2013-12-16
      • 1970-01-01
      相关资源
      最近更新 更多