我如何在 Django 中编写装饰器来检查两个单独的条件并相应地重定向?

How can I write a decorator in Django to check two separate conditions and redirect accordingly?

在我的项目中,一旦注册,用户必须先创建一个 Profile,然后才能访问站点的其余部分。我想要一个装饰器 @profile_decorator 来代替 @login_decorator.

如果用户是

  1. 未登录,重定向到 login URL
  2. 已登录,但没有 profile,重定向到 create profile URL
  3. 已登录,已 profile,允许继续查看

本文来自django.contrib.auth.decorators:

from functools import wraps

from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.shortcuts import resolve_url
from django.utils.decorators import available_attrs
from django.utils.six.moves.urllib.parse import urlparse


def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return _wrapped_view
    return decorator


def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator for views that checks that the user is logged in, redirecting
    to the log-in page if necessary.
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_authenticated(),
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator

这是我目前拥有的:

from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test

from django.conf.settings import CREATE_PROFILE_REDIRECT_URL

from .models import Profile


def profile_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator for views that checks that the user is logged in and has created
    a profile, redirecting to the log-in page if necessary.
    """
    actual_decorator = user_passes_test(
        test_func,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator


def test_func(u):
    if u.is_authenticated():
        if Profile.objects.filter(user=u).exists():
            return True
    return False

现在我很困惑,意识到我不知道如何使它对 1.2. 做出不同的反应。

编辑: login_required 装饰器有我想保留的附加功能——它将用户重定向回他们试图访问的原始页面登录成功。对不起,应该说开头。

我认为您尝试使用 user_passes_test 装饰器并不是在帮助自己。如果您自己从头开始创建装饰器,您会发现这会容易得多。

def profile_required(view_func):
    def wrapped(request, *args, **kwargs):
        if request.user.is_anonymous():
            path = request.build_absolute_uri()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(path, LOGIN_URL)
        else:
            try:
                profile = request.user.profile
            except Profile.DoesNotExist:
                return redirect(CREATE_PROFILE_REDIRECT_URL)
            else:
                return view_func(request, *args, **kwargs)
    return wrapped

这应该有效

from functools import wraps

def profile_required(view_func):
  def _decorator(request, *args, **kwargs):
    if request.user.is_anonymous():
        return redirect(LOGIN_URL)
    else:
        try:
            profile = Profile.object.get(user=request.user)
        except Profile.DoesNotExist:
            return redirect('userprofile_url')

    response = view_func(request, *args, **kwargs)

    return response
return wraps(view_func)(_decorator)


@profile_required
def your_func(request):
   # do something