[Django] user permission operation commands (1), django operation commands
To create a py file for testing, add the following code to the file.
# Coding: UTF-8 import OS. environ. setdefault ("DJANGO_SETTINGS_MODULE", "www. settings ") ''' when the Django version is greater than or equal to 1.7, add the following two statements: import djangodjango. setup () otherwise, the error django will be thrown. core. exceptions. appRegistryNotReady: Models aren't loaded yet. '''import djangofrom django. contrib. auth. models import Permission, User # User Permission if django. VERSION> = (1, 7): # automatically determines the VERSION of django. setup ()
Query all permissions of a user and convert the result to list
User. objects. get (username = ''). user_permissions.values () # method 1 list (User. objects. get (username =''). get_all_permissions () # method 2
Query all permissions and output them cyclically
c = Permission.objects.values()for i in c: print i
Add the specified permission. Note that content_type_id is of the int type and corresponds to the number of the model.
Permission. objects. create (name = 'add _ logentry ', content_type_id = 1, codename = 'can add log entry ')
# Example: Use the query permission statement to view {u'content _ type_id ': 1L, 'codename': u'add _ logentry', u'id': 1L, 'name': u'can add log entry '}] similar to this list,
Deletes a specified permission.
Permission.objects.get(codename='Can add log entry').delete()
Original article. For more information, see the source. Thank you!