Django implements form login

In the process of web development, almost all web site projects will involve the user's login function, which can use the form tag in html to implement a login box and input data to bind information. However, in the Django framework of "reaching and benefiting the world", rich components reduce a lot of work for us. One module named forms can implement forms from the python code level.

The flow chart of user login is as follows:

  1. Create a Django project Test, and create an application account
  2. Write the front-end page of login. / templates/account/login.html
  3. 3.
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
<p>Input your username and password</p>
<form action="." method="post">
    {% csrf_token %}
    {{ forms.as_p }}
    <input type="submit" value="Login">
 And add the template path in
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
  1. Create a file in. / account directory
from django import forms

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

4. Write view function

from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.shortcuts import render

from account.forms import LoginForm

def user_login(request):
    if request.method == "POST":
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            cd = login_form.cleaned_data
            user = authenticate(username=cd['username'],password=cd['password'])

            if user:
                '''After the user logs in, Django Will automatically call the default session Application,
                    //Save the user's id to the session. Usually, login and authenticate
                    //Use with ''
                return HttpResponse('Successfully logged in')
                return HttpResponse('Login failed')
            return HttpResponse("Illegal input")

    if request.method == "GET":
        login_form = LoginForm()
        return render(request,'account/login.html',{"forms":login_form})
  1. Migrate data files and start the service

Tags: Django Session Web Development Python

Posted on Mon, 04 May 2020 07:02:18 -0400 by kel