在视图中,您可以使用权限装饰器!
它们看起来像这样:
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...
或者这个,不仅仅是登录,即权限:
from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote')
def my_view(request):
...
如果您需要更复杂的场景(这些是我为自己制作的),您还可以定义自己的装饰器:
from django.contrib.auth.decorators import user_passes_test
from django.core.exceptions import PermissionDenied
def group_required(*group_names):
"""Requires user membership in at least one of the groups passed in."""
def in_groups(u):
if u.is_authenticated:
if u.groups.filter(name__in=group_names).exists() | u.is_superuser:
return True
return False
return user_passes_test(in_groups)
def superuser_only(function):
"""Limit view to superusers only."""
def _inner(request, *args, **kwargs):
if not request.user.is_superuser:
raise PermissionDenied
return function(request, *args, **kwargs)
return _inner
def has_group(user, group_name):
return user.groups.filter(name=group_name).exists()
...并像这样使用它们:
@login_required
@group_required('A', 'B')
def my_view(request):
....
为了在模板中使用,您可以定义自己的模板标签:
from django import template
register = template.Library()
@register.filter
def multiply(value, arg):
return (value * arg)