Django foundation Form component module

form component properties

  • Data validation function
  • Generate HTML code

Reference form component module

from django import forms                    #Introducing forms module
from django.forms import fields

data validation

Validation type

Data validation type Data validation method
String validation Fields.charfield (validation parameter)
Integer Digital Verification Fields.integerfield (validation parameter)
Mailbox validation Fields.emailfield (validation parameter)

Validation parameters

Data validation parameters Interpretation
required=True, Is it a null limit
max_length=8, Maximum length limit
min_length=8, Minimum length limit
invalid Format error, only used in error message

Custom error message

error_messages={"Validation parameters":"Custom error message"}

form validation instance

Create project

django-admin startproject Mydjango
cd Mydjango
python manage.py startapp APP

Project framework

[others remain the default ignore not shown]

Mydjango
    APP
        static
            jquery-3.3.1.min.js
        templates
            login01.html
        views.py
    Mydjango
        settings.py
        urls.py

login01.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>this from login_01</title>
    <script src="../static/jquery-3.3.1.min.js"></script>
    <style>
        form i{color: red;}
    </style>
</head>
<body>
<form action="login01.html" method="POST">
    {% csrf_token %}
    <!--Explanation:-->
        <!--HTML Page generation-->
            <!--{{ obj.user }} Fetching from back-end data, using forms Module generation user user input Other labels are similar-->
        <!--Error message feedback-->
            <!--{{ data_obj }} For all data sent to the back end-->
            <!--{{ data_obj.user }} For delivery to the back end, user Data for field-->
            <!--{{ data_obj.user.cleaned_data }} For delivery to the back end, user Data passed field validation-->
            <!--{{ data_obj.user.cleaned_errors }} For delivery to the back end, user Error message feedback of field validation failure, there may be multiple error messages-->
            <!--{{ data_obj.user.cleaned_errors.0 }} For delivery to the back end, user First error message fed back by error message of field validation failure-->
    <!--Similar to other fields-->
    <p>User:{{ obj.user }}<i>{{ data_obj.user.errors.0 }}</i></p>
    <p>Password:{{ obj.pwd }}<i>{{ data_obj.pwd.errors.0 }}</i></p>
    <p>Age:{{ obj.age }}<i>{{ data_obj.age.errors.0 }}</i></p>
    <p>Mailbox:{{ obj.email }}<i>{{ data_obj.email.errors.0 }}</i></p>
    <p><a><input type="submit" value="Submission"></a></p>
</form>
<script>

</script>
</body>
</html>

views.py

# -*- coding:utf8 -*-
from django.shortcuts import render,HttpResponse
from django import forms                    #Introducing forms module
from django.forms import fields

class From_submit(forms.Form):              #Inherit forms module
    #Use the froms module to verify the data, and keep the variable name consistent with the front-end name attribute

# Start ------------- forms module data validation------------------------------
    # Limit type - string maximum length minimum length, and cannot be empty
    user = fields.CharField(
        max_length=18,
        min_length=3,
        required=True,
        error_messages={
            'required':'User name cannot be empty',
            'max_length':'User name cannot exceed 18 characters',
            'min_length':'User name cannot be less than 3 characters',
        }
    )
    # Restriction type - string minimum length is 8 and cannot be empty
    pwd = fields.CharField(
        max_length=32,
        min_length=8,
        required=True,
        error_messages = {
        'required': 'Password cannot be empty',
        'max_length': 'Password cannot exceed 32 characters',
        'min_length': 'Password cannot be less than 8 characters',
        }
    )
    # Restriction type - integer, and cannot be empty
    age = fields.IntegerField(
        required=True,
        error_messages={
            'required': 'Age cannot be empty',
            'invalid':'There is a problem with the age format, it must be a number',
        }
    )
    # Restriction type - mailbox, and cannot be empty
    email = fields.EmailField(
        required=True,
        error_messages={
            'required': 'Mailbox cannot be empty',
            'invalid': 'There is a problem with the mailbox format',
        }
    )
# End ------------- forms module data validation------------------------------
def Data_sub(request):
    if request.method == "POST":
        data_obj = From_submit(request.POST)                            #Get all the data from
        if data_obj.is_valid():                                         #Judge whether the verification is successful
            print("Validation successful:",data_obj.cleaned_data)                   #The correct data of the user after successful verification [dictionary form]
            return HttpResponse("Submitted successfully!!!")
        else:
            print("Validation error:",data_obj.errors)                         #Error message returned from validation failure
            return render(request,"login01.html",{"data_obj":data_obj}) #Transfer the validation data to the front-end page for easy access to the data passing the validation and error feedback information
    else:
        obj = From_submit()                                             #Submission data with error information
        return render(request, "login01.html",{"obj":obj})              #Error message and submitted data return to submission page

urls.py

from django.contrib import admin
from django.urls import path,re_path
from APP import views
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('^login01.html$',views.Data_sub),
]

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'APP',
]
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'APP/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Operation test

python manage.py runserver

Keywords: Programming Django Python JQuery less

Added by Transwarp-Tim on Sun, 08 Dec 2019 03:46:48 +0200