• Form验证补充


    1.urls.py中的代码:

    urlpatterns=[

    path('fmindex.html/',fm.fmindex)
    ]

    2.index.html中代码:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    {% for item in obj %}
    {{ item.user }} {{ item.email }}

    {% endfor %}
    </body>
    </html>
    3.fm.py中代码:
    #_author:来童星
    #date:2020/5/5
    from django.shortcuts import render,HttpResponse
    from app01 import models
    from django import forms
    from django.forms import fields

    from django.core.exceptions import ValidationError

    class UserInfo(forms.Form):
    username=fields.CharField(label='用户名')
    email=fields.EmailField(label='密码')
    # def clean_username(self):
    #
    # value = self.cleaned_data['username']
    # if value == 'root':
    # return value
    # else:
    # raise ValidationError('你不是我的...')


    def clean(self):
    v1 = self.cleaned_data['username']
    v2 = self.cleaned_data['email']
    if v1 == "root" and v2 == "root@live.com":
    pass
    else:
    raise ValidationError('用户名或邮箱错误!!!')

    return self.cleaned_data

    # def _post_clean(self):
    # v1 = self.cleaned_data['username']
    # v2 = self.cleaned_data['email']
    # if v1 == "root" and v2 == "root@live.com":
    # pass
    # else:
    # self.add_error("__all__", ValidationError('用户名或邮箱错误...'))
    def fmindex(request):
    if request.method == "GET":
    obj = UserInfo()
    return render(request,'fmindex.html',{'obj': obj})
    elif request.method == "POST":
    obj = UserInfo(request.POST)
    obj.is_valid()
    # data = obj.clean()
    # obj.cleaned_data
    # print(obj.errors)
    return render(request, 'fmindex.html', {'obj': obj})
    运行结果:
    (1)定义
    clean函数的结果:


    (2)定义
    _post_clean效果

    (3)定义

    clean_username函数的结果:

  • 相关阅读:
    scrapy 项目搭建
    linux mysql -- ERROR! The server quit without updating PID file (/usr/local/mysql/data/localhost.localdomain.pid)
    linux 安装python 和pip
    转 Pycharm及python安装详细教程
    mysql在linux下的安装
    easyui datagrid动态修改editor时动态绑定combobox的数据
    easyui combobox 在datagrid中动态加载数据
    linux 安装tomcat
    CUBRID学习笔记23 关键字列表
    CUBRID学习笔记 22 插入数据
  • 原文地址:https://www.cnblogs.com/startl/p/12832624.html
Copyright © 2020-2023  润新知