简体   繁体   English

有没有办法让Django中的每个视图都执行一些操作?

[英]Is there a way to have something execute for every view in django?

I'm new to Django and coming from Rails, so that may explain my odd questions below: 我是Django的新手,来自Rails,因此可以在下面解释我的奇怪问题:

I have a main layout that has a sidebar that lists the latest updates to the site. 我的主布局有一个侧边栏,其中列出了该站点的最新更新。 That main layout is used for every page in my webapp so every template that is created extends main.html. 该主布局用于我的Web应用程序中的每个页面,因此创建的每个模板都扩展了main.html。

For the latest updates section, I just want to get the last 5 updates from posts to the web app every time a page is rendered. 对于“最新更新”部分,我只想在每次呈现页面时从发布到Web应用的最新5个更新。 I thought about making the sidebar do this through an ajax call once the page is loaded, but I thought this may not be my best option. 我曾考虑过要在页面加载后通过ajax调用来使侧边栏做到这一点,但我认为这可能不是我的最佳选择。

I also considered creating a tag to do this for me and then just calling the tag inside of main.html. 我还考虑过创建一个标签来为我执行此操作,然后仅在main.html内部调用该标签。 This is simple enough, but I'd have to write a lot of HTML inside of the tag code, which seems to be a little annoying (a lot of string appending and such, unless I'm wrong and there is a better way?) 这很简单,但是我必须在标记代码中编写很多HTML,这似乎有点烦人(很多字符串附加等等,除非我错了并且有更好的方法? )

I have read about Context Processors . 我已经阅读了有关上下文处理器的信息 This seemed to be exactly what I wanted, but it appears this may cause another issue where I have to pass a context_instance to every single render_to_response? 这似乎正是我想要的,但这似乎可能导致另一个问题,我必须将context_instance传递给每个单独的render_to_response? This appears to be a lot of code repeat and I'm trying to avoid that if possible. 这似乎是很多代码重复,如果可能的话,我试图避免这种情况。 Is there a way to just make render_to_response always take the RequestContext object without always having to specify it? 有没有一种方法可以使render_to_response始终采用RequestContext对象而不必始终指定它?

Are there any other ways to achieve having some code run for every view and eliminate the need to always pass data to a view? 还有其他方法可以为每个视图运行一些代码并消除始终向视图传递数据的需要吗?

Django 1.3添加了与render_to_response相同的render快捷方式,但自动使用了RequestContext

Templates is a appropriate place for this: the variant with custom tag and template inheritance is simple and convenient. 模板是适合的位置:具有自定义标签和模板继承的变量既简单又方便。 To avoid string appending use mini-template just for your tag: it is called inclusion tags . 为了避免附加字符串,请仅对您的标签使用迷你模板:这称为包含标签

我肯定会进行Ajax调用,就像创建一个小视图一样简单,该视图查询模型中的5条最新帖子,将它们序列化为json或xml数据,然后将它们返回到HttpRequest对象中。

您可以使用direct_to_template而不是render_to_response

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM