


Django user authentication system (3) groups and permissions
Django’s permission system is very simple, it can grant permissions to users or users in groups.
Django admin backend uses this permission system, but it can also be used in your own code. A User Will '
' Get All Permissions Granted to Each of 'Their Groups. Ermissions = Models.manytomanyField (Permission,Verbose_name = _ ('User permissions'), blank=True,
help_text=_('Specific permissions for this user.'), related_name="user_set", related_query_name="user")
You can access them like other django Models:
myuser.groups = [group_list]
myuser.groups.add(group, group, ...)
myuser.groups.remove(group, group, ...)
myuser.groups.clear()
myuser. user_permissions = [permission_list]
myuser.user_permissions.remove(permission, permission, ...)
myuser.user_permissions.clear()
Permissions
Permission exists as a Model. To establish a permission is to create an instance of the Permission Model.
@python_2_unicode_compatible
class Permission(models.Model):
"""
users and groups of users.
The permissions system is used by the Django admin site, but may also be
useful in your own code. The Django admin site uses permissions as follows:
- The "add" permission limits the user's ability to view the "add" form
and add an object.
- The "change" permission limits a user's ability to view the change
list, view the "change" form and change an object.
- The "delete" permission limits the ability to delete an object.
Permissions are set globally per type of object, not per specific object
instance. It is possible to say "Mary may change news stories," but it's
not currently possible to say "Mary may change news stories, but only the
ones she created herself" or "Mary may only change news stories that have a
certain status or publication date."
Three basic permissions -- add, change and delete -- are automatically
created for each Django model.
"""
name = models.CharField(_('name '), max_length=255)
content_type = models.ForeignKey(ContentType)
codename = models.CharField(_('codename'), max_length=100)
objects = PermissionManager()
class Meta:
verbose_name = _( 'permission')
verbose_name_plural = _('permissions')
unique_together = (('content_type', 'codename'),)
ordering = ('content_type__app_label', 'content_type__model',
'codename')
def __str__( self):
using using through through ’s ’ s ’ through ‐ ‐ ‐ off to )
def natural_key(self):
return (self.codename,) + self.content_type.natural_key()
natural_key.dependencies = ['contenttypes.contenttype']
fields fields
name: required. 50 characters or less, for example, 'Can Vote'
content_type: Required, a reference to the django_content_type database table, which contains records for each Model in the application.
codename: required, 100 characters or less, e.g., 'can_vote'.
If you want to create permissions for a Model:
from django.db import models
class Vote(models.Model):
...
class Meta:
permissions = (("can_vote", "Can Vote "),)
If this Model is in the application foo, the permission is expressed as 'foo.can_vote', check whether a user has the permission myuser.has_perm('foo.can_vote')
default permissions
If django.contrib.auth has been configured in INSTALLED_APPS, it will ensure that 3 default permissions are created for each Django Model in installed applications: add, change and delete.
These permissions will be created the first time you run manage.py migrate (syncdb before 1.7). At that time, all models will have permissions established. New models created after this will have these default permissions created when manage.py migrate is run again. These permissions correspond to the creation, deletion, and modification behaviors in the admin management interface.
Suppose you have an application foo with a model Bar, you can use the following method to test basic permissions:
add: user.has_perm('foo.add_bar')
change: user.has_perm('foo. change_bar')
delete: user.has_perm('foo.delete_bar')
Permission model (Permission model) is generally not used directly.
Groups
Groups also exist as Models:
@python_2_unicode_compatible
class Group(models.Model):
"""
Groups are a generic way of categorizing users to apply permissions, or
some other label, to those users. A user can belong to any number of
groups.
A user in a group automatically has all the permissions granted to that
group. group will have that permission.
Beyond permissions, groups are a convenient way to categorize users to
apply some label, or extended functionality, to them. For example, you
could create a group 'Special users', and you could write code that would
do special things to those users -- such as giving them access to a
members-only portion of your site, or sending them members-only email
messages.
"""
name = models.CharField(_ ('name'), max_length=80, unique=True)
permissions = models.ManyToManyField(Permission,
) verbose_name=_('permissions'), blank=True)
objects = GroupManager()
class Meta:
Verbose_name = _ ('Group')
Verbose_name_plural = _ ('Groups')
DEF __Str __ (Self):
Return Self.name
Def Nature_key (Sel):
Return (SELN f.Name,) 段 field fields:
name: required, 80 characters or less, e.g., 'Awesome Users'.
permissions: ManyToManyField to Permission
group.permissions = [permission_list]
group.permissions.add(permission, permission, ...)group.permissions.remove(permission, permission, ...)
group.permissions .clear()
Programmatically creating permissions
In addition to using Model meta to create permissions, you can also create them directly with code.
For example, create a can_publish permission for the BlogPost model in the myapp application:
from myapp.models import BlogPost
from django.contrib.auth.models import Group, Permissionfrom django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.create(codename='can_publish',
name='Can Publish Posts',
content_type=content_type)
Permissions can be given to a User object through Its user_permissions attribute or assigned to a Group through its permissions attribute.
Permission caching
User's permissions can be cached when checked. If a new permission is given to a User, it will not be checked if it is checked immediately. The easiest way is to re-fetch the User object.
from django.contrib.auth.models import Permission, User
from django.shortcuts import get_object_or_404
def user_gains_perms(request, user_id):
user = get_object_or_404(User, pk=user_id)
#Permission check will cache the current permissions Set
user.has_perm('myapp.change_bar')
permission = Permission.objects.get(codename='change_bar')
user.user_permissions.add(permission)
# Check permission cache set
user.has_perm(' myapp.change_bar') # False
# Request a new instance
user = get_object_or_404(User, pk=user_id)
# Permission cache is repopulated from the database
user.has_perm('myapp.change_bar') # True
. ..
Permission decorator
permission_required(perm[, login_url=None, raise_exception=False])
Check whether the user has a certain permission, similar to @login_required()
from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote', login_url='/loginpage/')
def my_view(request):
...
Permissions in the template
user's permissions are stored in template variables { { perms }} is the django.contrib.auth.context_processors.PermWrapper instance.
{{ perms.foo }}
The single attribute above is the proxy of User.has_module_perms. If the user has any permission in foo, it is True
{{ perms.foo.can_vote }}
The above two-level attribute query is a proxy of User.has_perm, if the user has the foo.can_vote permission, it is True .
For example:
{% if perms.foo %}
You have permission to do something in the You can vote! else %}
You don't have permission to do anything in the foo app.
{% endif %}
or:
{% if 'foo' in perms %}
{% if 'foo.can_vote' in perms %}
For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Steps to check the Django version: 1. Open a terminal or command prompt window; 2. Make sure Django has been installed. If Django is not installed, you can use the package management tool to install it and enter the pip install django command; 3. After the installation is complete , you can use python -m django --version to check the Django version.

Django and Flask are both leaders in Python Web frameworks, and they both have their own advantages and applicable scenarios. This article will conduct a comparative analysis of these two frameworks and provide specific code examples. Development Introduction Django is a full-featured Web framework, its main purpose is to quickly develop complex Web applications. Django provides many built-in functions, such as ORM (Object Relational Mapping), forms, authentication, management backend, etc. These features allow Django to handle large

Django is a complete development framework that covers all aspects of the web development life cycle. Currently, this framework is one of the most popular web frameworks worldwide. If you plan to use Django to build your own web applications, then you need to understand the advantages and disadvantages of the Django framework. Here's everything you need to know, including specific code examples. Django advantages: 1. Rapid development-Djang can quickly develop web applications. It provides a rich library and internal

How to check the django version: 1. To check through the command line, enter the "python -m django --version" command in the terminal or command line window; 2. To check in the Python interactive environment, enter "import django print(django. get_version())" code; 3. Check the settings file of the Django project and find a list named INSTALLED_APPS, which contains installed application information.

The differences are: 1. Django 1.x series: This is an early version of Django, including versions 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8 and 1.9. These versions mainly provide basic web development functions; 2. Django 2.x series: This is the mid-term version of Django, including 2.0, 2.1, 2.2 and other versions; 3. Django 3.x series: This is the latest version series of Django. Including versions 3.0, 3, etc.

How to upgrade Django version: steps and considerations, specific code examples required Introduction: Django is a powerful Python Web framework that is continuously updated and upgraded to provide better performance and more features. However, for developers using older versions of Django, upgrading Django may face some challenges. This article will introduce the steps and precautions on how to upgrade the Django version, and provide specific code examples. 1. Back up project files before upgrading Djan

django is the backend. Details: Although Django is primarily a backend framework, it is closely related to front-end development. Through features such as Django's template engine, static file management, and RESTful API, front-end developers can collaborate with back-end developers to build powerful, scalable web applications.

Django, Flask, and FastAPI: Which framework is right for beginners? Introduction: In the field of web application development, there are many excellent Python frameworks to choose from. This article will focus on the three most popular frameworks, Django, Flask and FastAPI. We will evaluate their features and discuss which framework is best for beginners to use. At the same time, we will also provide some specific code examples to help beginners better understand these frameworks. 1. Django: Django
