Python - Django - form 组件常用的字段和字段参数

邮箱:

views.py:

from django import forms
from django.forms import widgets


class RegForm(forms.Form):
    email = forms.EmailField(
        label="邮箱",
        widget=widgets.EmailInput(),
    )

 

单选按钮:

views.py:

from django import forms
from django.forms import widgets


class RegForm(forms.Form):
    hobby = forms.ChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "羽毛球")),  # 选项
        label="爱好",
        initial=2,  # 默认选择 2
        widget=widgets.RadioSelect()  # 设置为单选按钮
    )

运行结果:

 

 

单选(默认):

views.py:

from django import forms
from django.forms import widgets


class RegForm(forms.Form):
    hobby = forms.ChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "羽毛球")),  # 选项
        label="爱好",
        initial=2,  # 默认选择 2
        widget=widgets.Select()  # 写没写都一样
    )

运行结果:

 

 

多选:

views.py:

from django import forms
from django.forms import widgets


class RegForm(forms.Form):
    hobby = forms.MultipleChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "羽毛球"), (4, "排球")),  # 选项
        label="爱好",
        initial=[2, 4],  # 默认选择 2、4
        widget=widgets.SelectMultiple()  # 设置为多选
    )

运行结果:

 

 

单项复选框:

views.py:

from django import forms
from django.forms import widgets


class RegForm(forms.Form):
    rem_pwd = forms.ChoiceField(
        label="记住密码",
        initial="checked",  # 默认为勾选
        widget=widgets.CheckboxInput()  # 设置为单项复选框
    )

运行结果:

 

 

多选复选框:

views.py:

from django import forms
from django.forms import widgets


class RegForm(forms.Form):
    rem_pwd = forms.MultipleChoiceField(
        choices=((1, "篮球"), (2, "足球"), (3, "羽毛球"), (4, "排球")),  # 选项
        label="爱好",
        initial=[1, 3],
        widget=widgets.CheckboxSelectMultiple()  # 设置为多选复选框
    )

运行结果:

 

posted @ 2019-09-05 22:39  Sch01aR#  阅读(482)  评论(0编辑  收藏  举报