【问题标题】:Django: Is there a way to set global views? For example enable data for a sidebar through all URLSDjango:有没有办法设置全局视图?例如,通过所有 URL 为侧边栏启用数据
【发布时间】:2024-05-22 03:05:01
【问题描述】:

我正在构建一个 Django 应用程序,它是一个非常基本的博客,到目前为止它非常棒。我得到了cmets,标签等。但有一件事困扰着我:我无法获得我想要工作的侧边栏。我使用 django.views.generic.date_based 通用视图,这是我的 urls.py 博客:

    urlpatterns = patterns('django.views.generic.date_based',
        (r'(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail',dict(info_dict, slug_field='slug',template_name='blog/detail.html')),

 (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-\w]+)/$', 'object_detail', dict(info_dict, template_name='blog/list.html')),

 (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/$','archive_day',dict(info_dict,template_name='blog/list.html')),

 (r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$','archive_month', dict(info_dict, template_name='blog/list.html')),

 (r'^(?P<year>\d{4})/$','archive_year', dict(info_dict, template_name='blog/list.html')),

 (r'^$','archive_index', dict(info_dict, template_name='blog/list.html')),

)

当我使用传递了“archive_index”的 URL 时,我可以轻松地为侧边栏打印最新条目,但是当我输入帖子时,我将使用只有“object_detail”可用的*条目之一。这使我的侧边栏条目消失。这个问题的最佳解决方案是什么?有没有办法让一些对象在全球范围内可用?通过视图或其他方式。

【问题讨论】:

    标签: python django


    【解决方案1】:

    人们使用模板标签做类似的事情。 documentation for custom template tags 可能会有所帮助,还有一个很棒的小教程here

    或者,您可以使用context processors - 但这会增加每个请求的开销,这可能不是必需的。

    【讨论】:

    • 非常感谢,真的很有帮助! :)