我有一个带有字段# This are the proxy settings we use for activator
# Multiple proxy hosts can be used by separating them with a '|' sign
# Do not enclose the proxy host(s) in quotes
#-Dhttp.proxyHost=10.10.78.22
#-Dhttp.proxyPort=3128
# Here we configure the hosts which should not go through the proxy.# You should include your private network, if applicable.
-Dhttp.nonProxyHosts="localhost|127.0.0.1"
# These are commented out, but if you need to use authentication for your proxy, please fill these out.
#-Dhttp.proxyUser=(my_username)
#-Dhttp.proxyPassword=(my_password)
的模型类Department
。我有另一个模型name
,其中包含Student
的外键。我想根据部门控制对Department
个对象的访问。也就是说,具有编辑部门名称" CS"只能编辑那些字段。如何在Django中实现这一目标? (我使用的是django 1.8,python3)
修改
Student
此外,我还在添加新部门时动态创建所需权限。(例如:如果新条目的department.name为' CS',2等权限,例如' view_CS'和' edit_CS'将被创建)
答案 0 :(得分:3)
基于http://django-guardian.readthedocs.org/en/v1.2/userguide/assign.html#for-group
class Department(models.Model):
name = models.CharField(_('department name'), max_length=255)
class Meta:
permissions = (
('view', 'View department'),
('edit', 'Edit department'),
)
视图中的某个地方:
from django.contrib.auth.models import Group
cs_department = Department.objects.get(name='cs_department')
cs_department_group = Group.objects.create(name=cs_department.name)
assign_perm('view', cs_department_group, cs_department)
assign_perm('edit', cs_department_group, cs_department)
request.user.groups.add(cs_department_group)
print(request.user.has_perm('view', cs_department)) # True
print(request.user.has_perm('edit', cs_department)) # True
答案 1 :(得分:-1)
由于我的应用程序很大,我无法承受更改整个数据引用以容纳@madaohan答案的权限。
这种访问控制机制可以很容易地用来定义自定义模型管理器(docs)和中间件来登录模型中的用户对象(Check this link),