django usage rights in the template

In settings.TEMPLATES.OPTIONS.content_processors, because adding a django.contrib.auth.context_processors.auth context processor.

 

 

 

Thus you can directly obtain all rights of users by perms in the template, the following sample code:

{%  if perms.front.add_article  % }

  <a href="/article/add/"> Add Article </a>

{% endif %}

 

 

1, defined in app01 / templates / index.html inside template

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    Home
    {% if perms.app01.add_article %}
        < A href = "#"  > add articles </ A >
    {% endif %}

</body>
</html>

 

2, in the index view is defined app01 / views.py Lane

# Use the template permissions 
DEF index (Request):
     return   the render (Request, ' index.html ' )

3, define a route

from django.contrib import admin
from django.urls import path
from app01 import views as app01_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path("test/", app01_views.test),
    path("login/", app01_views.my_login, name = "login"),
    path("logout/", app01_views.my_logout, name = "logout"),
    path("profile/", app01_views.profile, name="profile"),
    path("add_permission/", app01_views.add_permission, name="add_permission" ),
    path("oper_permission/", app01_views.operate_permission, name="oper_permission" ),
    path("add_article/", app01_views.add_article, name="add_article" ),
    path("oper_group", app01_views.operate_group, name="oper_group"),
    path("", app01_views.index, name="index"),
]

 

4, access http://127.0.0.1:8080/ the following effects

 

 

Description, users have permission to add_article

 

 

 

 

 

 

 

 

 

 

5, delete permissions auth_group_permissions 19 inside out, and then access http://127.0.0.1:8080/

 

 

 Since there is no 19 group1 corresponding permission, and all pages are not displayed permission to add articles

 

 

6, directly in app01_user_user_permissions table, after adding 1 to 19 users permissions, then access http://127.0.0.1:8080/

 

Add article appeared authority

 

 

 

 

Guess you like

Origin www.cnblogs.com/harryTree/p/11827799.html