我想为我的django应用程序添加每个对象的权限,但我似乎无法实现基本功能。我也在使用python社交身份验证,但我不认为这会成为身份验证的问题。用户仍然正常工作。
我似乎做得很正确,但当我尝试向组添加权限时,它失败了,并出现DoesNotExist错误。
为了稍微解释一下我的设计,每个项目都有一个领导者和一组成员。成员组定义项目的每个成员将拥有的权限。领导在成员组中,但最终也会添加特殊权限,允许他们做标准成员不能做的事情。
我的型号.py
class Project(models.Model):
# Leader of the project
project_name = models.CharField(max_length=200, unique=True)
# The url for the stash repository
#project_repo = models.
# Date the project was created
date_created = models.DateTimeField(auto_now=True)
# Person in charge of the project
project_lead = models.ForeignKey(User, related_name='%(class)s_lead_set')
# Group of members to use for permission checking
members = models.ForeignKey(Group, null=True, default=None)
class Meta:
permissions = (
('edit_project', 'Edit Project'),
)
我的观点.py
@login_required
def create(request):
if request.method== "POST":
form = NewProjectForm(request.POST)
if form.is_valid():
# Create the new project
project = Project(**form.cleaned_data)
project.project_lead = request.user
# Create a user group
members = Group.objects.create(name = project.project_name)
members.save()
# Add the members group to the project
project.members = members
project.save()
#ERROR OCCURS HERE
assign_perm('edit', members, project)
members.save()
从我的项目设置.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'thelibrary',
'home',
'projects',
'social.apps.django_app.default',
'guardian',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.core.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
)
AUTHENTICATION_BACKENDS = (
'social.backends.google.GoogleOAuth2',
'guardian.backends.ObjectPermissionBackend',
'django.contrib.auth.backends.ModelBackend',
)
全堆栈跟踪
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/guardian/shortcuts.py", line 91, in assign_perm
return model.objects.assign_perm(perm, user, obj)
File "/usr/lib/python2.7/site-packages/guardian/managers.py", line 33, in assign_perm
permission = Permission.objects.get(content_type=ctype, codename=perm)
File "/usr/lib64/python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/django/db/models/query.py", line 357, in get
self.model._meta.object_name)
DoesNotExist: Permission matching query does not exist.
您应该更改
assign_perm('edit', members, project)
至
assign_perm('edit_project', members, project)