簡體   English   中英

如何將用戶重定向到登錄頁面,直到他們完成授權?

[英]How can I redirect the user to the login page until they complete the authorization?

我找到了這樣一段代碼,但我不明白它是如何工作的。 如果您在未執行授權的情況下將路徑設置為另一個頁面 - 此頁面將打開。

@login_required
def my_view(login_url='/'):
    return HttpResponseRedirect('/config')

我需要你的幫助。

(如何進行授權)

class LoginView(View):

    def get(self, request, *args, **kwargs):
        form = LoginForm(request.POST or None)
        context = {
            'form': form
        }
        return render(request, 'manager/login.html', context)

    def post(self, request, *args, **kwargs):
        form = LoginForm(request.POST or None)
        context = {
            'form': form
        }
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return HttpResponseRedirect('/config')
        return render(request, 'manager/login.html', context)

您想將所有未經身份驗證的用戶重定向到您的登錄頁面,直到他們登錄?
我認為使用 MiddleWares 是處理此問題的最佳方式,因為您想在所有視圖上執行此操作。

from django.http import HttpResponseRedirect
from django.urls import reverse


class AuthRequiredMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('login')) # Your login page url
        return None   

在你的 settings.py 中,你需要添加你的 MiddleWare:

MIDDLEWARE_CLASSES = (
    ...
    'path.to.your.AuthRequiredMiddleware',
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM