django_Form组件基本用法

一、Form组件初识

  • 引用类from django import forms
  • 继承forms.Form
  • 继承后里面的变量名和html标签name属性,一一对应关系
class FM(forms.Form):
    user = forms.CharField()
    pwd = forms.CharField()
    email = forms.EmailField()
  • view中方法使用,创建对象obj = FM(request.POST),判断是否为真Valid = obj.is_valid(),获取对象全部内容obj.cleaned_data,获取展示页面的提示信息obj.errors
def login(request):
    if request.method == "GET":
        return render(request,"login.html")
    elif request.method == "POST":
        obj = FM(request.POST)
        Valid = obj.is_valid()
        if Valid:
            print(obj.cleaned_data)
        else:
            #print(obj.errors.as_json)
            erro_msg = obj.errors
            return render(request,'login.html',{"erro":erro_msg})
  • 其中obj.errors.as_json打印的格式为

  • 如何让默认提示变成英文
  • error_messages 错误信息的属性
  • required是否为空
  • max_length 最长
  • min_length 最短
  • invalid 格式
    user = forms.CharField(error_messages={'required':'用户名不能为空'})
    pwd = forms.CharField(
        max_length=12,
        min_length=6,
        error_messages={'required':'密码不能为空','max_length':'密码长度小于12','min_length':'密码长度大于6'}
    )
    email = forms.EmailField(error_messages={'required':'邮箱不能为空','invalid' :'邮箱格式不对'})

view 层的代码

{% csrf_token %}

{{ erro.user.0 }}

{{ erro.pwd.0 }}

{{ erro.email.0 }}

二、Form组件升级

from django.shortcuts import render,redirect
from django import forms
# Create your views here.
class FM(forms.Form):
    user = forms.CharField(error_messages={'required':'用户名不能为空'})
    pwd = forms.CharField(
        max_length=12,
        min_length=6,
        error_messages={'required':'密码不能为空','max_length':'密码长度小于12','min_length':'密码长度大于6'}
    )
    email = forms.EmailField(error_messages={'required':'邮箱不能为空','invalid' :'邮箱格式不对'})
def login(request):
    if request.method == "GET":
        obj = FM()
        return render(request,"login.html",{"obj":obj})
    elif request.method == "POST":
        obj = FM(request.POST)
        Valid = obj.is_valid()
        if Valid:
            print(obj.cleaned_data)
        else:
            return render(request,'login.html',{"obj":obj})

html


        {% csrf_token %}
        

{{ obj.user }}{{ obj.erros.user.0 }}

{{ obj.pwd }}{{ obj.erros.pwd.0 }}

{{ obj.email }}{{ obj.erros.email.0 }}

其中在html页面中ul展示{{obj.as_ul}},p标签展示{{obj.as_p}}
table展示


        {{obj.as_table}

你可能感兴趣的:(django_Form组件基本用法)