Python|使用 django 进行表单验证
先决条件:Django 安装 | Django 简介
Django 使用 MVT 模式。因此需要创建数据模型(或表)。对于每个表,都会创建一个模型类。
假设有一个表单将用户名、性别和文本作为用户的输入,任务是验证数据并保存。
在 django 中可以这样做,如下所示:
Python
from django.db import models
# model named Post
class Post(models.Model):
Male = 'M'
FeMale = 'F'
GENDER_CHOICES = (
(Male, 'Male'),
(FeMale, 'Female'),
)
# define a username filed with bound max length it can have
username = models.CharField( max_length = 20, blank = False,
null = False)
# This is used to write a post
text = models.TextField(blank = False, null = False)
# Values for gender are restricted by giving choices
gender = models.CharField(max_length = 6, choices = GENDER_CHOICES,
default = Male)
time = models.DateTimeField(auto_now_add = True)
Python
from django.forms import ModelForm
from django import forms
from formValidationApp.models import *
# define the class of a form
class PostForm(ModelForm):
class Meta:
# write the name of models for which the form is made
model = Post
# Custom fields
fields =["username", "gender", "text"]
# this function will be used for the validation
def clean(self):
# data from the form is fetched using super function
super(PostForm, self).clean()
# extract the username and text field from the data
username = self.cleaned_data.get('username')
text = self.cleaned_data.get('text')
# conditions to be met for the username length
if len(username) < 5:
self._errors['username'] = self.error_class([
'Minimum 5 characters required'])
if len(text) <10:
self._errors['text'] = self.error_class([
'Post Should Contain a minimum of 10 characters'])
# return any errors if found
return self.cleaned_data
Python
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.shortcuts import HttpResponse
from . import views
urlpatterns = [
path('', views.home, name ='index'),
]
Python
from .models import Post
from .forms import PostForm
from .import views
from django.shortcuts import HttpResponse, render, redirect
def home(request):
# check if the request is post
if request.method =='POST':
# Pass the form data to the form class
details = PostForm(request.POST)
# In the 'form' class the clean function
# is defined, if all the data is correct
# as per the clean function, it returns true
if details.is_valid():
# Temporarily make an object to be add some
# logic into the data if there is such a need
# before writing to the database
post = details.save(commit = False)
# Finally write the changes into database
post.save()
# redirect it to some another page indicating data
# was inserted successfully
return HttpResponse("data submitted successfully")
else:
# Redirect back to the same page if the data
# was invalid
return render(request, "home.html", {'form':details})
else:
# If the request is a GET request then,
# create an empty form object and
# render it into the page
form = PostForm(None)
return render(request, 'home.html', {'form':form})
html
{% load bootstrap3 %}
{% bootstrap_messages %}
Basic Form
Form
创建数据模型后,需要在数据库中反映更改以执行此操作,请运行以下命令:
python manage.py makemigrations
这样做会编译模型,如果没有发现任何错误,则会在迁移文件夹中创建一个文件。稍后运行下面给出的命令,最终将保存到迁移文件中的更改反映到数据库中。
python manage.py migrate
现在可以创建一个表单。假设用户名长度不应小于 5,post 长度应大于 10。那么我们使用所需的验证规则定义PostForm类,如下所示:
Python
from django.forms import ModelForm
from django import forms
from formValidationApp.models import *
# define the class of a form
class PostForm(ModelForm):
class Meta:
# write the name of models for which the form is made
model = Post
# Custom fields
fields =["username", "gender", "text"]
# this function will be used for the validation
def clean(self):
# data from the form is fetched using super function
super(PostForm, self).clean()
# extract the username and text field from the data
username = self.cleaned_data.get('username')
text = self.cleaned_data.get('text')
# conditions to be met for the username length
if len(username) < 5:
self._errors['username'] = self.error_class([
'Minimum 5 characters required'])
if len(text) <10:
self._errors['text'] = self.error_class([
'Post Should Contain a minimum of 10 characters'])
# return any errors if found
return self.cleaned_data
至此,数据模型和Form类已经定义完毕。现在的重点将放在如何实际使用上面定义的这些模块。
首先,通过这个命令在 localhost 上运行
python manage.py runserver
在浏览器中打开http://localhost:8000/ ,然后它会在urls.py文件中搜索,寻找''路径
urls.py文件如下所示:
Python
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.shortcuts import HttpResponse
from . import views
urlpatterns = [
path('', views.home, name ='index'),
]
基本上,这会将 ' ' url 与在views.py文件中定义的函数主页相关联。
view.py 文件:
Python
from .models import Post
from .forms import PostForm
from .import views
from django.shortcuts import HttpResponse, render, redirect
def home(request):
# check if the request is post
if request.method =='POST':
# Pass the form data to the form class
details = PostForm(request.POST)
# In the 'form' class the clean function
# is defined, if all the data is correct
# as per the clean function, it returns true
if details.is_valid():
# Temporarily make an object to be add some
# logic into the data if there is such a need
# before writing to the database
post = details.save(commit = False)
# Finally write the changes into database
post.save()
# redirect it to some another page indicating data
# was inserted successfully
return HttpResponse("data submitted successfully")
else:
# Redirect back to the same page if the data
# was invalid
return render(request, "home.html", {'form':details})
else:
# If the request is a GET request then,
# create an empty form object and
# render it into the page
form = PostForm(None)
return render(request, 'home.html', {'form':form})
home.html模板文件
html
{% load bootstrap3 %}
{% bootstrap_messages %}
Basic Form
Form
在浏览器中打开http://localhost:8000/显示如下,
如果提交了一个用户名长度小于 5 的表单,它会在提交时出错,对于填写的 Post Text 也是如此。下图显示了表单在提交无效表单数据时的行为。