Django相当于Rails application_controller [英] Django equivalent to Rails application_controller
问题描述
在Rails中,我使用application_controller来控制用户会话,并创建对象来填充网站的某些部分,如菜单。
In Rails, I used the application_controller to control things like user sessions, and create objects to populate parts of the site like the menu.
应该如何完成在Django中,既然没有一种应用视图呢?您是否必须使用自定义过滤器和部分模板,例如在基本模板中执行此操作?
How should this be done in Django, since there is no kind of "application view"? Do you have to use custom filters and partial templates to be included, for instance in the base template to do this?
我也一直在看基于类的视图,但是不确定是否是这样的。
I have also been looking at class-based views, but am unsure if that is it.
推荐答案
有几种方法可以实现:
- 模板标签
- 上下文处理器
- 基于类的视图
- 中间件
- Template Tags
- Context Processors
- Class Based Views
- Middleware
这只是取决于你需要做什么。 request.user
始终存在于请求对象中,即使它是匿名用户,因此您不必对模板中的该对象进行特殊访问,服务器端代码。
It just depends on what you're needing to do. request.user
is always present in the request object, even if it's an anonymous user, so you don't have to do anything special to access that object from within a template or server-side code.
包含标签与您在Rails中渲染部分一样接近。
信号和基于类的视图接近于您在控制器过滤器中找到的内容。
Inclusion tags are as close as you'll get to render partial in Rails. Signals and Class-Based views are close to what you'd find in controller filters.
当我学习Django(我从Rails去Django)时,我发现最有帮助的一本书是实用Django项目。 Django的最终指南也可免费使用。
One of the books I found most helpful when learning Django (I went to Django from Rails) was Practical Django Projects. The Definitive Guide to Django is also available for free.
这篇关于Django相当于Rails application_controller的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!