Django 自定义验证字段方法

先看项目结构
在这里插入图片描述
一、准备工作
django的cmd命令行创建项目

django-admin startproject form_test5
cd form_test5
python manage.py startapp front

settings.py里面需更改的配置


#注册app
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'front'
]

#注释掉csrf保护
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

#注明html的path默认路径
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'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',
            ],
        },
    },
]

#数据库配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME':'test3',
        'USER':'root',
        'PASSWORD':'123456',
        'PORT':'3306',
        'HOST':'localhost',
    }
}

二、模型搭建
models.py里面创建模型

from django.db import models

class User(models.Model):
    username = models.CharField(max_length=100)
    telephone = models.CharField(max_length=11)
#完成此步后注意数据库生成 python manage.py makemigrations  和 python manage.py migrate

forms.py 里面的校验模型

from django import forms
from django.core import validators
from .models import User

class RegisterForm(forms.Form):
    username = forms.CharField(max_length=100)
    telephone = forms.CharField(validators=[validators.RegexValidator(r'1[3-9]\d{9}',message='请输入正确手机号码')])
    pwd1 = forms.CharField(max_length=11,min_length=6,error_messages={'min_length':'请输入至少六位数密码'})
    pwd2 = forms.CharField(max_length=11,min_length=6,error_messages={'min_length':'请输入至少六位数密码'})

#以clean开头的方法,在项目运行is_valid()时,会运行改方法
    def clean_telephone(self):
        telephone = self.cleaned_data.get('telephone')
        exists = User.objects.filter(telephone=telephone).exists()
        if exists:
            raise forms.ValidationError(message='%s手机号码已被注册'%telephone)
        return telephone

#在所有校验完成后 运行自定义clean()方法
    def clean(self):
        cleaned_data = super().clean()
        pwd1 = cleaned_data.get('pwd1')
        pwd2 = cleaned_data.get('pwd2')
        if pwd1 != pwd2:
            raise forms.ValidationError(message='两次密码不一致')

templates下的regiter.html内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>register</title>
</head>
<body>
<form action="" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>电话:</td>
            <td><input type="text" name="telephone"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="pwd1"></td>
        </tr>
        <tr>
            <td>确认密码:</td>
            <td><input type="password" name="pwd2"></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="提交"></td>
        </tr>
    </table>

</form>
</body>
</html>

views.py内容

from django.shortcuts import render
from django.views import View
from .models import User
from .forms import RegisterForm
from django.http import HttpResponse


def index(request):
    return render(request,'index.html')

class RegisterView(View):
    def get(self,request):
        return render(request,'register.html')

    def post(self,requset):
        form = RegisterForm(requset.POST)
        if form.is_valid():
            username = form.cleaned_data.get('telephone')
            telephone = form.cleaned_data.get('telephone')
            User.objects.create(username=username,telephone=telephone)
            return HttpResponse('注册成功')
        else:
            print(form.errors.get_json_data())
            return HttpResponse('注册失败')

ulrs.py映射url关系

from django.urls import path
from front import views
urlpatterns = [
    path('',views.index),
    path('register/',views.RegisterView.as_view())
]

运行项目
在这里插入图片描述
在这里插入图片描述
注册成功

再次输入同样电话
在这里插入图片描述
注册失败
后台显示错误日志
在这里插入图片描述

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 创作都市 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读