In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you the example analysis of groups and permissions in the Django user authentication system, I believe that most people do not know much about it, so share this article for your reference. I hope you will gain a lot after reading this article. Let's learn about it together.
The permission system of Django is very simple, it can give permissions to users in users or groups.
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 any other django Model:
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, and to create a permission is to create an instance of Permission Model.
@ 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 django_content_type database table, which contains a record of the Model in each application.
Codename: required, 100 characters or less, for example, 'can_vote'.
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', checks whether a user has permission myuser.has_perm ('foo.can_vote').
Default permission default permissions
If django.contrib.auth is already 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 the first time you run manage.py migrate (syncdb before 1.7). At that time, all models will establish permissions. A new models created after that creates these default permissions when you run manage.py migrate again. These permissions correspond to the create, delete, and modify behaviors in the admin management interface.
Suppose you have an application foo with a model Bar, you can test basic permissions in the following ways:
Add: user.has_perm ('foo.add_bar')
Change: user.has_perm ('foo.change_bar')
Delete: user.has_perm ('foo.delete_bar')
The permission model (Permission model) is generally not used directly.
Group Groups
Groups also exist as 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, '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 permissions directly in code.
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 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 assigned to a User object through its user_permissions property or to a Group through its permissions property.
Permission caching
The permission check of User can be cached. If a new permission is assigned to a User, it will not be checked out if it is checked immediately. The easiest way is to re-fetch User the object.
From django.contrib.auth.models import Permission, Userfrom 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 caches the current permission 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 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 templat
The permissions of user are saved in the template variable {{perms}}, which is an instance of django.contrib.auth.context_processors.PermWrapper.
{{perms.foo}}
The single attribute above is the proxy for User.has_module_perms. True if user has any of the permissions in foo
{{perms.foo.can_vote}}
The above two-level property query is a proxy for User.has_perm, or True if the user has foo.can_vote permission.
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%} {% endif%} above are all the contents of this article entitled "sample Analysis of groups and permissions in Django user Authentication system". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.