django的权限问题
django的权限默认是针对每个model的
比如foo这个model
django的权限问题
django的权限默认是针对每个model的
比如foo这个model
* add: user.has_perm('foo.add_bar')
* change: user.has_perm('foo.change_bar')
* delete: user.has_perm('foo.delete_bar')
可以在admin模块的用户管理里面看的很清楚
自定义的话需要对自己的model进行元数据的编辑
比如
[ccn lang="python" tab_size="4" theme="blackboard" width="800" ]
class Task(models.Model):
...
class Meta:
permissions = (
("can_view", "Can see available tasks"),
("can_change_status", "Can change the status of tasks"),
("can_close", "Can remove a task by setting its status as closed"),
)
[/ccn]
使用方法:
[ccn lang="python" tab_size="4" theme="blackboard" width="800" ]
1 from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote', login_url='/loginpage/')
def my_view(request):
...
2 from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote')
def my_view(request):
...
[/ccn]
当然在模板里也一样可以使用
认证的
[ccn lang="python" tab_size="4" theme="blackboard" width="800" ]
{% if user.is_authenticated %}
Welcome, {{ user.username }}. Thanks for logging in.
{% else %}
Welcome, new user. Please log in.
{% endif %}
[/ccn]
权限的
[ccn lang="python" tab_size="4" theme="blackboard" width="800" ]
{% 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 %}
[/ccn]