search

Home  >  Q&A  >  body text

python - [Django] How to get user information for each template

For example, if you use Django to build a website, most pages will contain user information, such as username, avatar, etc.

But it’s impossible for me to pass a user variable into the context for each view, right?

How do I usually achieve this requirement?

漂亮男人漂亮男人2700 days ago1009

reply all(5)I'll reply

  • typecho

    typecho2017-07-05 10:36:29

    You need to worry too much, you don’t need to write them one by one manually, it is already there by default, just use it, for example: {{user.username}}
    But there is no custom field information such as avatar.
    Or you can customize a context_processors.py to return the information you want, and then import it in settings.py. There is no need to return in every function

    reply
    0
  • PHP中文网

    PHP中文网2017-07-05 10:36:29

    如果你是使用的auth.login()登录的话,你可以在任何一个模板里直接使用user对象
    如{{user.username}}

    reply
    0
  • PHP中文网

    PHP中文网2017-07-05 10:36:29

    It should be {{request.user.username}}.
    And django supports setting global variables

    reply
    0
  • 習慣沉默

    習慣沉默2017-07-05 10:36:29

    After the user logs in, the user information will generally be stored in request.user. There is no need to pass the user variable into the context. The premise is that django.template.context_processors.request is referenced in settings

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-07-05 10:36:29

    Additional point: If a fixed part of content appears on many pages, you can use template inheritance to extract the same parts, and modify the content of the template through extends and include.

    reply
    0
  • Cancelreply