• python测试开发django-107.form组件widgets(radio/checkbox/单选多选下拉框/日历控件)


    前言

    form 组件widgets可以生成页面上常见的控件:radio/checkbox/单选多选下拉框/日历控件等

    生成页面上控件

    models.py设计模型

    from django.db import models
    
    # Create your models here.
    
    class Detail(models.Model):
        user = models.CharField(max_length=30, blank=True, null=True)
        age = models.IntegerField(blank=True, null=True)
        email = models.EmailField(blank=True, null=True)
        city = models.CharField(max_length=30, blank=True, null=True)
        GENDER_CHOICES = (
            ('男', '男'),
            ('女', '女'),
        )
        gender = models.CharField(
            max_length=30,
            choices=GENDER_CHOICES
        )
        fancy = models.CharField(max_length=30, blank=True, null=True)
        comment = models.TextField()
        birth = models.DateTimeField()
    

    DetailFrom 类

    # 作者-上海悠悠 QQ交流群:717225969
    # blog地址 https://www.cnblogs.com/yoyoketang/
    from django.forms import widgets
    from .models import Detail
    from django.views import View
    from django import forms
    from django.shortcuts import render
    
    
    class DetailFrom(forms.Form):
        user = forms.CharField(
                            label="姓名",
                            required=False,
                            max_length=12,
                            min_length=3,
                            error_messages={"required": '不能为空'},
                )
        age = forms.IntegerField(label="年龄", max_value=200, min_value=0)
        gender = forms.CharField(
            label="性别",
            widget=widgets.RadioSelect(
                choices=[
                    ('男', '男'),
                    ('女', '女')
                ]
            ),     # Radio 单选
            initial='男'
        )
        email = forms.EmailField(label="邮箱",)
        city = forms.CharField(
            label="城市",
            widget=widgets.Select(choices=[
                ("北京", "北京"),
                ("上海", "上海"),
                ("深圳", "深圳"),
                ("杭州", "杭州"),
            ]),
            initial="上海"
        )
    
        birth = forms.DateTimeField(label="出生年月",
                                    widget=forms.DateInput(attrs={'type': 'date',
                                                                  'value': '2021-01-01'}))
        comment = forms.CharField(label="评论",
                                  widget=forms.Textarea)
        # 单选 checkbox
        xx = forms.CharField(
                            label="是否勾选",
                            widget=widgets.CheckboxInput(),
                            )
        # 多选 checkbox
        fancy = forms.MultipleChoiceField(label="爱好",
                                          initial=[2, ],
                                          choices=((1, 'Python'), (2, 'Selenium'), (3, "Appium")),
                                          widget=widgets.CheckboxSelectMultiple
                                        )
    
        # 多选下拉框
        fancy2 = forms.MultipleChoiceField(label="爱好2",
                                           initial=[2, ],
                                           choices=((1, 'Python'), (2, 'Selenium'), (3, "Appium"))
                                            )
    
    

    views.py视图

    # 作者-上海悠悠 QQ交流群:717225969
    # blog地址 https://www.cnblogs.com/yoyoketang/
    
    class DetailView(View):
    
        def get(self, request):
            form_obj = DetailFrom()
            return render(request, "detail.html", locals())
    
        def post(self, request):
            form_obj = DetailFrom(request.POST)
            if form_obj.is_valid():
                data = form_obj.cleaned_data()
                ...
                msg = "保存成功"
                return render(request, "detail.html", locals())
    
            else:
                # 全局钩子自定义错误提示获取
                print(form_obj.errors.get('__all__')[0])
                error_msg = form_obj.errors.get('__all__')[0]
    
            return render(request, "detail.html", locals())
    

    模板

    detail.html模板

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>详情页面</title>
        <style>
            ul li{
                list-style: none;
            }
        </style>
    </head>
    <body>
    <form action="" method="POST" id="detail-form" >
        {% csrf_token %}
        {% for field in form_obj %}
            {% if field.label == "性别" %}
                {{ field.label_tag }}
                {{ field.0 }} {{ field.1 }}
    
            {% elif field.label == "爱好" %}
                {{ field.label_tag }}
                {% for f in field %}
                     {{ f }}
                {% endfor %}
    
            {% else %}
                <p>
                {{ field.label_tag }}
                {{ field }}
                {{ field.errors }}
            </p>
    
            {% endif %}
    
        {% endfor %}
        <p>
            {% if msg %}
                {{ msg }}
    
            {% endif %}
    
        </p>
        <p>
            <input type="submit" value="提交" >
        </p>
    </form>
    </body>
    </html>
    

    页面生成效果

    widgets常用的类型

    TextInput(Input)
    NumberInput(TextInput)
    EmailInput(TextInput)
    URLInput(TextInput)
    PasswordInput(TextInput)
    HiddenInput(TextInput)
    Textarea(Widget)
    DateInput(DateTimeBaseInput)
    DateTimeInput(DateTimeBaseInput)
    TimeInput(DateTimeBaseInput)
    CheckboxInput
    Select
    NullBooleanSelect
    SelectMultiple
    RadioSelect
    CheckboxSelectMultiple
    FileInput
    ClearableFileInput
    MultipleHiddenInput
    SplitDateTimeWidget
    SplitHiddenDateTimeWidget
    SelectDateWidget

  • 相关阅读:
    autofac meta
    RazorEngine 3.6.5.0
    pfx 转 snk
    git
    Nlog Layout
    NLog 传递参数
    扫描.net dll引用dll
    vbox android x86 分辨率
    Andriod x86 4,4
    .net cli 源码
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/15004528.html
Copyright © 2020-2023  润新知