[Django] About users that can be used on template

Introduction

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 overriddenget_context_data ()` to add the variable? I had a question here, so I did some research.

Conclusion

The variables that can be used in the template are stored in the context (= {: , .....}), and this context roughly includes the following two types of variables.

  1. Variables passed using render function etc. in views.py
  2. Variables defined in the file specified by'context_processers' specified in the OPTION of TEMPLATES in settings.py

ʻ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 asrequest, perm, and message`.

Where it is stored

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`

Storage location of ʻuser`

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 returning'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.

(reference)

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

[Django] About users that can be used on template
Python standard module that can be used on the command line
About the matter that the re.compiled object can be used for the re.match pattern
I created a template for a Python project that can be used universally
Hide the warning that zsh can be used by default on Mac
File types that can be used with Go
Functions that can be used in for statements
[Hackathon] About making a tool that can be CD on Raspberry Pi [Convenient tool]
Basic algorithms that can be used in competition pros
Python knowledge notes that can be used with AtCoder
ANTs image registration that can be used in 5 minutes
Deep learning course that can be crushed on site
How to filter foreign keys that can be selected on the Django admin screen
Goroutine (parallel control) that can be used in the field
Goroutine that can be used in the field (errgroup.Group edition)
Scripts that can be used when using bottle in Python
Install Mecab and CaboCha on ubuntu16.04LTS so that it can be used from python3 series
[Django] Field names, user registration, and login methods that can be used in the User model
How to set variables that can be used throughout the Django app-useful for templates, etc.-
Which octal literals can be used depends on the programming language
About character string handling that can be placed in JSON communication
Confirmation that rkhunter can be installed
Python standard input summary that can be used in competition pro
About the matter that torch summary can be really used when building a model with Pytorch
Easy padding of data that can be used in natural language processing
Acoustic signal processing module that can be used with Python-Sounddevice ASIO [Application]
Acoustic signal processing module that can be used with Python-Sounddevice ASIO [Basic]
Django: Test Middleware that depends on another Middleware
I wanted to quickly create a mail server that can be used freely with postfix + dovecot on EC2
A personal memo of Pandas related operations that can be used in practice
Easy program installer and automatic program updater that can be used in any language
Django # 2 (template)
Summary of scikit-learn data sources that can be used when writing analysis articles
I made a familiar function that can be used in statistics with Python
How to install a Python library that can be used by pharmaceutical companies
Linux command that can be used from today if you know it (Basic)
"Gazpacho", a scraping module that can be used more easily than Beautiful Soup
Until youtube-dl can be used with Synology (DS120j)
Building Sphinx that can be written in Markdown
Even monkeys can understand! About Intents on discord.py!
List packages that can be updated with pip
The problem that the ifconfig command cannot be used
Overview and useful features of scikit-learn that can also be used for deep learning
Introduced "Glances" command, a monitoring tool that can be understood at a glance, on Mac
Convert images from FlyCapture SDK to a form that can be used with openCV
Summary of statistical data analysis methods using Python that can be used in business
Introduction of automatic image collection package "icrawler" (0.6.3) that can be used during machine learning
[Python] Introduction to web scraping | Summary of methods that can be used with webdriver
Morphological analysis and tfidf (with test code) that can be done in about 1 minute
File sharing server made with Raspberry Pi that can be used for remote work
Simple statistics that can be used to analyze the effect of measures on EC sites and codes that can be used in jupyter notebook