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 of ‘ ‘their groups.‘), related_name="user_set", related_query_name="user") user_permissions = 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()
Permission Permissions
Permissions exist as a model. Creating a permission is to create a permission model instance.
@python_2_unicode_compatibleclass 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 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): return "%s | %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 modelsclass 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_compatibleclass 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. 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 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 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 BlogPostfrom django.contrib.auth.models import Group, Permissionfrom django.contrib.contenttypes.models import ContentTypecontent_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, userfrom Django. shortcuts import get_object_or_404def 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 the 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(‘polls.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 %} <p>You have permission to do something in the foo app.</p> {% if perms.foo.can_vote %} <p>You can vote!</p> {% endif %} {% if perms.foo.can_drive %} <p>You can drive!</p> {% endif %}{% else %} <p>You don‘t have permission to do anything in the foo app.</p>{% endif %}
Or:
{% if ‘foo‘ in perms %} {% if ‘foo.can_vote‘ in perms %} <p>In lookup works, too.</p> {% endif %}{% endif %}
Django User Authentication System (3) groups and permissions