Python |使用django进行表单验证

先决条件 : Django安装 | Django简介 Django使用MVT模式。因此需要创建数据模型(或表)。对于每个表,都会创建一个模型类。 假设有一种形式 用户名 , 性别 文本 作为用户的输入,任务是验证数据并保存它。 在django,可以这样做,如下所示:

null

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 manage.py makemigrations

这样做会编译模型,如果没有发现任何错误,就会在迁移文件夹中创建一个文件。稍后运行下面给出的命令,最终将保存到迁移文件中的更改反映到数据库中。

python manage.py migrate

现在可以创建一个表单。假设用户名长度不应小于5,帖子长度应大于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


到目前为止,数据模型和表单类都已定义。现在重点将放在如何实际使用上面定义的这些模块上。 首先,通过以下命令在localhost上运行

python manage.py runserver

打开 http://localhost:8000/ 在浏览器中,然后它将在 网址。py 文件,正在查找“”路径 网址。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与函数相关联 定义如下: 意见。py 文件 意见。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})


家html 模板文件

html

{% load bootstrap3 %}
{% bootstrap_messages %}
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >Basic Form</ title >
< meta charset = "utf-8" />
< meta name = "viewport" content = "width=device-width, initial-scale=1, shrink-to-fit=no" >
</ script >
</ script >
</ head >
< body style = "padding-top: 60px;background-color: #f5f7f8 !important;" >
< div class = "container" >
< div class = "row" >
< div class = "col-md-4 col-md-offset-4" >
< h2 >Form</ h2 >
< form action = "" method = "post" >< input type = 'hidden' />
{%csrf_token %}
{% bootstrap_form form %}
<!-This is the form variable which we are passing from the function
of home in views.py file. That's the beauty of Django we
don't need to write much codes in this it'll automatically pass
all the form details in here
->
< div class = "form-group" >
< button type = "submit" class = "btn btn-default " >
Submit
</ button >
</ div >
</ form >
</ div >
</ div >
</ div >
</ body >
</ html >


开放 http://localhost:8000/ 在浏览器中显示以下内容:,

图片[1]-Python |使用django进行表单验证-yiteyi-C++库

如果提交了用户名长度小于5的表单,则在提交时会给出一个错误,同样,对于填写的帖子文本也会给出一个错误。下图显示了表单在提交无效表单数据时的行为。

图片[2]-Python |使用django进行表单验证-yiteyi-C++库

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享