Django user authentication system (3) groups and permissions

Source: Internet
Author: User
Django's permission system is simple. it can grant users or users in groups permissions. Django's permission system is simple. it can grant users or users in groups permissions.

This permission system is used in the Django admin background, but it can also be used in your own code.

The User object has two ManyToManyField fields: groups and user_permissions.

Groups = models. ManyToManyField (Group, verbose_name = _ ('groups '),
Blank = True, help_text = _ ('The groups this user belongs to. A user will'
'Get all permissions granted to each'
'Their groups .'),
Related_name = "user_set", related_query_name = "user ")
User_permissions = models. ManyToManyField (Permission,
Verbose_name = _ ('User permission'), 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 ()

Permission Permissions

Permissions exist as a Model. Creating a Permission is to create a Permission Model instance.

@ 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 permission 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
Ones she created herself "or" Mary may only change news stories that have
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 ):
Return "% s | % s" % (
Six. text_type (self. content_type.app_label ),
Six. text_type (self. content_type ),
Six. text_type (self. name ))

Def natural_key (self ):
Return (self. codename,) + self. content_type.natural_key ()
Natural_key.dependencies = ['contenttypes. contenttype']

Field fields

Name: required. 50 characters or less, for example, 'can vote'

Content_type: Required. a reference to the table in the django_content_type Database. The table contains the Model record of each application.

Codename: required, 100 characters or less, for example, '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 the Model is in the application foo, the permission is expressed as 'Foo. can_vote ', and 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 ensures that three default permissions are created for each Django Model in installed applications: add, change, and delete.

These permissions will be created when you first run manage. py migrate (syncdb before 1.7. At that time, all models will create permissions. The new models created after this will create these default permissions when you run manage. py migrate again. These permissions correspond to the creation, deletion, and modification actions on the admin management interface.

Suppose you have an app foo with a model Bar, and you can test the basic permissions using the following methods:

Add: user. has_perm ('foo. add_bar ')
Change: user. has_perm ('foo. change_bar ')
Delete: user. has_perm ('foo. delete_bar ')
Permission model is generally not directly used.

Group Groups

A group also exists as a Model:

@ 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
Groups.

A user in a group automatically has all the permissions granted to that
Group. For example, if the group Site editors has the permission
Can_edit_home_page, any user in that group will have that permission.

Beyond permissions, groups are a convenient way to categorize users
Apply some label, or extended functionality, to them. For example, you
Cocould create a group 'special users', and you cocould write code that wo'd
Do special things to those users -- such as giving them access to
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 = _ ('permission'), blank = True)

Objects = GroupManager ()

Class Meta:
Verbose_name = _ ('Group ')
Verbose_name_plural = _ ('groups ')

Def _ str _ (self ):
Return self. name

Def natural_key (self ):
Return (self. name ,)

Field fields:

Name: required, 80 characters or less, for example, 'awessome 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 directly use code to create permissions.

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)

A permission can be granted to a User object through its user_permissions attribute or a Group through its permissions attribute.

Permission cache

Users can be cached during permission check. if a new permission is granted to a User, immediate check will not be performed. The simplest way is to refetch 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)
# The permission check caches the current permission set
User. has_perm ('myapp. change_bar ')

Permission = Permission. objects. get (codename = 'change _ bar ')
User. user_permissions.add (permission)

# Check the 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 a user has a certain permission, similar to @ login_required ()

From django. contrib. auth. decorators import permission_required

@ Permission_required ('lls. can_vote ', login_url ='/loginpage /')
Def my_view (request ):
...

Permissions in the template

The user permission is stored in the template variable {perms}, which is the django. contrib. auth. context_processors.PermWrapper instance.

{Perms. foo }}

The preceding single attribute is the proxy of User. has_module_perms. True if the user has any permission in foo

{Perms. foo. can_vote }}

The above two-level property query is the proxy of User. has_perm. if the User has foo. can_vote permission, the value is True.

For example:

{% If perms. foo %}

You have permission to do something in the foo app.


{% If perms. foo. can_vote %}

You can vote!


{% Endif %}
{% If perms. foo. can_drive %}

You can drive!


{% Endif %}
{% 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 %}

In lookup works, too.


{% Endif %}

These are the groups and permissions of the Django user authentication system (III). For more information, see PHP Chinese network (www.php1.cn )!

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.