6.4-6.5 Use form authentication to improve the login page

Previously, a custom class was used to implement the login logic. Now, the built-in form validation of django is used, and the view that inherits django is used to implement the login page.

 

The content of users > views.py is:

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from .models import UserProfile
from django.db.models import Q
from django.views.generic.base import View
from .forms import LoginForm


# Create your views here.


def user_login(request):
    if request.method == 'GET':
        return render(request, 'login.html', {})
    if request.method == 'POST':
        user_name = request.POST.get('username', '')
        pass_word = request.POST.get( ' password ' , '' )
         #successfully returns user, failure returns None 
        user = authenticate(username=user_name, password= pass_word)
         if user is  not None:
            login(request, user)   #Direct login 
            return redirect( ' home ' )
         else :
             return render(request, ' login.html ' , { ' msg ' : ' The username or password is incorrect. ' })


#Achieve both username and email can log in 
class CustomBackend(ModelBackend):
     def authenticate(self, request, username=None, password=None, ** kwargs):
         try :
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html', {})

    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():

            user_name = request.POST.get('username', '')
            pass_word = request.POST.get( ' password ' , '' )
             #successfully returns user, failure returns None 
            user = authenticate(username=user_name, password= pass_word)
             if user is  not None:
                login(request, user)   #Login directly 
                return redirect( ' home ' )
             else :
                 return render(request, ' login.html ' , { ' msg ' : ' The username or password is incorrect. ' })
         else :
             return render(request , ' login.html ' , { ' login_form ' : login_form})

 

if login_form.is_valid(): 

It means that if the form validation passes, it will enter the next layer, and if the form content validation fails, it will jump out

Add the forms.py file to the users module to verify the data entered in the login input:

from django import forms


class LoginForm(forms.Form):
    username = forms.CharField(required=True)
    password = forms.CharField(required=True, min_length=8)

 

From django.views.generic.base import View View

in django has get and post methods, so you don't have to judge by yourself.

login_form = LoginForm(request.POST)

uses django's Form form authentication to verify the data from request.POST. For example, if the password length is less than 8 digits, an error will be returned directly, and no database query will be performed.

Finally, the modification of urls.py:

from django.contrib import admin
from django.urls import path
import xadmin
from django.views.generic import TemplateView
from users.views import LoginView

urlpatterns = [
    path('xadmin/', xadmin.site.urls),
    path('', TemplateView.as_view(template_name='index.html'), name='home'),
    # path('login/', TemplateView.as_view(template_name='login.html'), name='login'),
    # path('login/', user_login, name='login'),
    path('login/', LoginView.as_view(), name='login'),
]
LoginView.as_view() 

uses LoginView's as_view() method to implement login authentication and login logic.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325215229&siteId=291194637