In Django, if you want to display the name of the currently logged-in user on the screen, you can do it by doing {{user.username}}
or {{user.get_username}}
on the template. But why can I use this variable ʻuser even though I haven't passed it to templets using the
renderfunction in views.py or overridden
get_context_data ()` to add the variable? I had a question here, so I did some research.
The variables that can be used in the template are stored in the context (= {
ʻUseris a variable that corresponds to the explanation of 2. There are other main variables that can be used without specifying it in views.py, such as
request,
perm, and
message`.
First, take a look at setting.py.
config/setting.py
#
#abridgement
#
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
#
#abridgement
#
The following four files are specified by TEMPLATES.OPTIONS.context_processors in setting.py.
django.template.context_processors.debug
django.template.context_processors.request
Whereabouts of django.contrib.auth.context_processors.auth
・ ・ ・ ・ ・ ・ ʻuser
django.contrib.messages.context_processors.messages`
python:django.contrib.auth.context_processors
#
#abridgement
#
def auth(request):
"""
Return context variables required by apps that use Django's authentication
system.
If there is no 'user' attribute in the request, use AnonymousUser (from
django.contrib.auth).
"""
if hasattr(request, 'user'):
user = request.user
else:
from django.contrib.auth.models import AnonymousUser
user = AnonymousUser()
return {
'user': user,
'perms': PermWrapper(user),
}
By return
ing'user': user
, ʻuser can be used in the template. After taking out the ʻusername
attribute in ʻuser as ʻuser.username
or instantiating the AnonymousUser class, use the get_user method in the class to set ʻuser.get_username` to change the logged-in user name. It can be displayed.
At the bottom is the get_username function.
python:django.contrib.auth.models
class AnonymousUser:
id = None
pk = None
username = ''
is_staff = False
is_active = False
is_superuser = False
_groups = EmptyManager(Group)
_user_permissions = EmptyManager(Permission)
def __str__(self):
return 'AnonymousUser'
def __eq__(self, other):
return isinstance(other, self.__class__)
def __hash__(self):
return 1 # instances always return the same hash value
def __int__(self):
raise TypeError('Cannot cast AnonymousUser to int. Are you trying to use it in place of User?')
def save(self):
raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
def delete(self):
raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
def set_password(self, raw_password):
raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
def check_password(self, raw_password):
raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.")
@property
def groups(self):
return self._groups
@property
def user_permissions(self):
return self._user_permissions
def get_user_permissions(self, obj=None):
return _user_get_permissions(self, obj, 'user')
def get_group_permissions(self, obj=None):
return set()
def get_all_permissions(self, obj=None):
return _user_get_permissions(self, obj, 'all')
def has_perm(self, perm, obj=None):
return _user_has_perm(self, perm, obj=obj)
def has_perms(self, perm_list, obj=None):
return all(self.has_perm(perm, obj) for perm in perm_list)
def has_module_perms(self, module):
return _user_has_module_perms(self, module)
@property
def is_anonymous(self):
return True
@property
def is_authenticated(self):
return False
def get_username(self):
return self.username
Recommended Posts