在每个页面中从数据库提供下拉列表
Serving Dropdown from database in every page
我正在处理这个项目,它有 2 个应用程序。
主应用程序:其中包含页面(主页、关于、联系方式)
库存应用程序:具有模型(类别、产品、标签等)
现在导航栏始终显示类别下拉菜单,其中列出了 5 个类别或其中的多个类别,并带有一个按钮以查看所有类别。
我正在使用基于 class 的视图,我可以覆盖 get_context_data 方法并查询类别模型并将其添加到每个页面呈现的上下文中,但我想知道是否有更好的方法解决这个问题的方法。
看看context processors。它可以自动将数据添加到上下文中,每个模板都可以访问它。您需要编辑 settings.py 以包含自定义函数的路径。
来自文档:
It’s a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.
Custom context processors can live anywhere in your code base. All Django cares about is that your custom context processors are pointed to by the 'context_processors' option in your TEMPLATES setting — or the context_processors argument of Engine if you’re using it directly.
我正在处理这个项目,它有 2 个应用程序。 主应用程序:其中包含页面(主页、关于、联系方式) 库存应用程序:具有模型(类别、产品、标签等)
现在导航栏始终显示类别下拉菜单,其中列出了 5 个类别或其中的多个类别,并带有一个按钮以查看所有类别。
我正在使用基于 class 的视图,我可以覆盖 get_context_data 方法并查询类别模型并将其添加到每个页面呈现的上下文中,但我想知道是否有更好的方法解决这个问题的方法。
看看context processors。它可以自动将数据添加到上下文中,每个模板都可以访问它。您需要编辑 settings.py 以包含自定义函数的路径。
来自文档:
It’s a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.
Custom context processors can live anywhere in your code base. All Django cares about is that your custom context processors are pointed to by the 'context_processors' option in your TEMPLATES setting — or the context_processors argument of Engine if you’re using it directly.