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?
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
PHP中文网2017-07-05 10:36:29
It should be {{request.user.username}}.
And django supports setting global variables
習慣沉默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
我想大声告诉你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.