Home > Backend Development > Python Tutorial > Django user authentication system (3) groups and permissions

Django user authentication system (3) groups and permissions

黄舟
Release: 2016-12-23 17:42:55
Original
1367 people have browsed it

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.add(permission, permission, ...)

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):
"""

The permissions system PRovides a way to assign permissions to specific

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, Permission

from 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)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template