加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Django form组件

发布时间:2020-12-20 12:48:35 所属栏目:Python 来源:网络整理
导读:一、前提 1、导入模块 # form组件 from django import forms # widgets form组件的小工具 from django.forms import widgets 2、定义类 class RegForm(forms.Form): 二、字段(类的属性) 1、用户名 # 用户名 name = forms.CharField( label = " 用户名 " , #

一、前提

1、导入模块

# form组件
from django import forms
# widgets form组件的小工具
from django.forms import widgets

2、定义类

class RegForm(forms.Form):

二、字段(类的属性)

1、用户名

 # 用户名
    name = forms.CharField(
        label="用户名",# 最小长度
        min_length=4,max_length=8,# input的种类,添加属性
        widget=widgets.TextInput(attrs={"class": "form-control"}),# 校验的错误信息的重新,默认是英文
        error_messages={
            "min_length": "用户名长度不能少于4位","max_length": "用户名长度不能大于8位",# 不能为空
            "required": "用户名长度不能为空",}
    )

2、密码

    # 密码,render_value= True,当校验不通过时,保留原有内容
    pwd = forms.CharField(
        label="密码",min_length=8,max_length=10,# input的类型
        widget=widgets.PasswordInput(attrs={"class": "form-control"},render_value=True),error_messages={
            "min_length": "密码长度不能少于8位","max_length": "密码长度不能大于10位","required": "密码不能为空",}
    )

3、邮件

 # 邮件
    email = forms.EmailField(
        label="邮件",# input类型 
        widget=widgets.EmailInput(
            attrs={"class": "form-control"},),error_messages={
            "required": "邮件不能为空"
        }
    )

4、radio

    # 注意 ChoiceField RadioSelect
    gender = forms.ChoiceField(
        label="性别",widget=widgets.RadioSelect(),choices=((1,""),(2,"")),initial=1
    )

5、checkbox(单选)

?

6、checkbox(多选)

4、select(单选)

 # 城市,choice为选项的内容,initaial为初始的内容
    city = forms.ChoiceField(
        label="城市",widget=widgets.Select(attrs={"class": "form-control"},choices=models.City.objects.all().values_list("id","name"),initial=1
    )

5、select(多选)

    # 多选select ,注意 MultipleChoiceField,SelectMultiple()
    city2 = forms.MultipleChoiceField(
        label="城市",widget=widgets.SelectMultiple(),initial=[1,2],)

总结:单选用ChoiceField,多选用MultipleChoiceField

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读