1. 程式人生 > 實用技巧 >Django 快速實現登入功能,完成login_required驗證

Django 快速實現登入功能,完成login_required驗證

業務場景:某網站下很多站點URL,基於必須登入的頁面下,首現會跳轉到登陸頁面進行登入,URL中明顯記錄了下一站點的路由,但實際登入後未進行跳轉。

解決方案:利用django自帶的認證方式,只需新增一個form和一個html即可。

總結:
整體實現方式是使用django自帶的認證方式,加form表單(自己寫的表單有些問題,各種msg處理都得重新寫)。另外需區分admin登入頁面與自定義的認證頁面,我們引用admin頁面的認證可以達到簡化程式碼的操作,但是簡單嘗試呼叫發現並不可行。所以總歸來說需要自己寫一個登入頁面,django幫我們認證,其他路由的認證只需要呼叫即可,並且在驗證完成後跳轉回訪問的頁面。

urls.py:

from django.contrib.auth.views import LoginView
from django.contrib.auth.views import LogoutView
from apt_main.forms import MyAuthenticationForm

urlpatterns = [
    path(r'accounts/login/', LoginView.as_view(template_name="login.html",authentication_form=MyAuthenticationForm), name='login'),
    path(r'accounts/logout/', LogoutView.as_view(), name='logout'),
    ...
    

forms.py:

from django.contrib.auth.forms import AuthenticationForm

class MyAuthenticationForm(AuthenticationForm):
    def __init__(self, *args, **kwargs):
        super(MyAuthenticationForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['placeholder'] = u'Username'
        self.fields['password'].widget.attrs['placeholder'] = u'Password'

login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登入</title>
</head>
<body>
<h1>歡迎登入</h1>
<form method="post" action="{% url 'login' %}?next={{ request.GET.next }}">
    {% csrf_token %}
    {{ form }}
    <div class="form-group" align="center">
        <div>
            <button type="submit" class="btn btn-viper">Login</button>
        </div>
	</div>
</form>
</body>
</html>

之後的頁面中,若添加了@login_required,則將採用此頁面進行登入

views.py:

@login_required(login_url="/accounts/login/")
def index(requests):
    return HttpResponse("20000")

------------------class寫法---------------------------

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView

class IndexViews(LoginRequiredMixin, TemplateView):
    def get(self, request, *args, **kwargs):
        return HttpResponse("2000")

備註:

LoginRequiredMixin等同於@login_required(login_url="/accounts/login/")。前者直接讀取settings關於LOGIN_URL設定,該類內部應該也有相應的變數進行修改,後者預設也讀取LOGIN_URL設定

urls.py:

    ...
    path(r'index/', views.index,name="tf_download"),
]

---------------class寫法-------------
    path(r"index/", views.IndexViews.as_view())