Use the authentication data method in Django templates

Source: Internet
Author: User
This article mainly introduces how to use authentication data in Django templates. Django is the most popular Pythonweb development framework, if you need a friend, you can refer to the user currently logged in and his or her permissions. you can use RequestContext in the context of the template.

Note:

Technically, only variables such as RequestContext are available. And the TEMPLATE_CONTEXT_PROCESSORS setting contains "django. core. context_processors.auth" (this is the case by default), these variables can be used in the template context. When the TEMPLATE_CONTEXT_PROCESSORS settings contain "django. core. context_processors.auth" (this is the case by default), these variables can be used in the template context.

When RequestContext is used, the current User (a user instance or an AnonymousUser instance) is stored in the template variable {User:

{% if user.is_authenticated %} 

Welcome, {{ user.username }}. Thanks for logging in.

{% else %}

Welcome, new user. Please log in.

{% endif %}

The permission information of these users is stored in the {perms} template variable.

You can use perms objects in two ways. You can use {perms. polls} to check whether a user has any permissions for a specific application. you can also use {perms. polls. can_vote} to check whether a user has specific permissions.

In this way, you can check the permission in the {% if %} statement in the template:

{% if perms.polls %} 

You have permission to do something in the polls app.

{% if perms.polls.can_vote %}

You can vote!

{% endif %}{% else %}

You don't have permission to do anything in the polls app.

{% endif %}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.