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

Str*_*ire 3 python authentication django decorator

在我的项目中,一旦注册,用户必须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
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止:

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
Run Code Online (Sandbox Code Playgroud)

现在我只是感到困惑,意识到我不知道如何使它对1.和做出不同的反应2.

编辑:login_required装饰具有附加功能,我想保留-它重定向登录成功后,用户返回到他们尝试了全新的页面访问。对不起,应该说开始。

Dan*_*man 5

我不认为您尝试使用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
Run Code Online (Sandbox Code Playgroud)