从模板django中的请求获取数据

问题描述:

我想知道从请求会话中获取数据是一个坏主意,还是将数据解析为dict上下文并进行渲染(需要针对每个视图进行处理)会更好?

I wonder is it a bad idea to get data from request session or is it better to parse the data into dict context and render it (Need to do it for each view)?

常见的做法是通过视图中的上下文发送所需的内容.

It's common practice to send what you need through the context in the view.

我觉得它为您提供了更多的安全性/确定性,因为您可以将逻辑保持在应该显示的位置,而不用在模板中检查请求中的内容.

I feel like it gives you a little more security/certainty in what you're doing because you can keep your logic in the view where it should be rather than doing any checks in the template for things being in the request.

编辑

仅当您希望很少做某事时,以上内容才适用.如果您定期向模板中添加请求的元素,则确实应该像其他人所建议的那样,编写上下文处理器以使您所需的内容可用于所有视图.看一下文档; TEMPLATE_CONTEXT_PROCESSORS

The above is only true if you're looking to do something rarely. If you're regularly adding an element of the request to your templates you should indeed, as everybody else suggests, be writing context processors to make what you require available to all views. Take a look at the docs; TEMPLATE_CONTEXT_PROCESSORS

也请阅读django书籍的这一章,因为它会非常有帮助;第9章:高级模板

Also give this chapter of the django book a read as it'll be very helpful; Chapter 9: Advanced Templates

特别是本节;

编写自己的上下文处理器的指南

以下是滚动自己的一些提示:

Here are a few tips for rolling your own:

  • 让每个上下文处理器负责最小的功能子集.使用多个处理器很容易,因此您最好将功能分成逻辑部分,以备将来重用.

  • Make each context processor responsible for the smallest subset of functionality possible. It’s easy to use multiple processors, so you might as well split functionality into logical pieces for future reuse.

请记住,TEMPLATE_CONTEXT_PROCESSORS中的任何上下文处理器将在由该设置文件提供支持的每个模板中可用,因此请尝试选择不太可能与模板的变量名冲突的变量名可能是独立使用.由于变量名称区分大小写,因此对处理器提供的变量使用所有大写字母并不是一个坏主意.

Keep in mind that any context processor in TEMPLATE_CONTEXT_PROCESSORS will be available in every template powered by that settings file, so try to pick variable names that are unlikely to conflict with variable names your templates might be using independently. As variable names are case-sensitive, it’s not a bad idea to use all caps for variables that a processor provides.

只要它们位于您的Python路径上,它们在文件系统上的位置并不重要,因此您可以从TEMPLATE_CONTEXT_PROCESSORS设置中指向它们.话虽如此,惯例是将它们保存在您的应用程序或项目中的context_processors.py文件中.

It doesn’t matter where on the filesystem they live, as long as they’re on your Python path so you can point to them from the TEMPLATE_CONTEXT_PROCESSORS setting. With that said, the convention is to save them in a file called context_processors.py within your app or project.