7.5. Views Decorators
@login_required
@cache_page
@csrf_exempt
@method_decorator
@permission_required
@require_http_methods
@require_POST
- view only accepts the GET method@require_GET
- view only accepts the POST method@require_safe
- view only accepts the GET and HEAD methods
7.5.1. login_required
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...
7.5.2. permission_required
from django.contrib.auth.decorators import permission_required
@permission_required('customer.add_choice')
def my_view(request):
...
If the raise_exception
parameter is given, the decorator will raise
PermissionDenied
, prompting the 403 (HTTP Forbidden) view instead of
redirecting to the login page.
If you want to use raise_exception but also give your users a chance to
login first, you can add the login_required()
decorator:
from django.contrib.auth.decorators import login_required, permission_required
@login_required
@permission_required('customer.add_choice', raise_exception=True)
def my_view(request):
...
7.5.3. user_passes_test
from django.contrib.auth.decorators import user_passes_test
def email_check(user):
return user.email.endswith('@example.com')
@user_passes_test(email_check)
def my_view(request):
...
7.5.4. require_http_methods
from django.views.decorators.http import require_http_methods
@require_http_methods(['GET', 'POST'])
def my_view(request):
# do something
pass
7.5.5. require_GET
from django.views.decorators.http import require_http_methods
@require_GET
def my_view(request):
# do something
pass
7.5.6. require_POST
from django.views.decorators.http import require_http_methods
@require_POST
def my_view(request):
# do something
pass