Django equivalent to Rails application_controller

2019-06-05 01:56发布

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.

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.

1条回答
The star\"
2楼-- · 2019-06-05 02:20

There are several ways to accomplish this:

  • Template Tags
  • Context Processors
  • Class Based Views
  • Middleware

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.

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.

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.

查看更多
登录 后发表回答