zoukankan      html  css  js  c++  java
  • Django Form 表单

    Form 表单功能

    生成HTML表单元素
    检查表单元素的合法性
    验证如果错误,重复显示表单
    数据类型转换

    Form相关的对象

    Widget 渲染成HTML元素的工具
    Field Form对象中的一个字段
    Form 一系列Field对象的集合
    Form Media 用来渲染表单的CSS与JS资源

    继承forms.Form实现表单功能

    Form实例方法is_valid()检查表单是否合法, 合法数据会被放到cleaned_data属性中

     1 #继承创建表单示例
     2     
     3     #form.py
     4     from django import forms
     5     
     6  7     class RemarkForm(forms.Form):
     8         subject = forms.CharField(max_length=100 ,label='留言标题')
     9         mail = forms.EmailField(label='电子邮件')
    10         topic = forms.ChoiceField(choices=(
    11              ('leve1', '差评'),
    12              ('leve2', '中评'),
    13              ('leve3', '好评'),
    14             ),label='选择评分')
    15         message = forms.CharField(label='留言内容',widget=forms.Textarea)
    16         cc_myself = forms.BooleanField(required=False ,label='订阅该贴')
    17 #也可以在与model结合
    18     
    19     #student.py
    20     class StudentModel(models.Model):
    21         sname = models.CharField(max_length = 100,)
    22     #模型与表单关联需要导入ModelForm模块
    23     from django.forms import ModelForm
    24      
    25     class StudentForm(ModelForm):
    26         class Meta:
    27         model = StudentModel
    28         fields = ('sname') #必须与model类的名字一样
    29 #也可以在与model结合
    30     
    31     #student.py
    32     class StudentModel(models.Model):
    33         sname = models.CharField(max_length = 100,)
    34     #模型与表单关联需要导入ModelForm模块
    35     from django.forms import ModelForm
    36      
    37     class StudentForm(ModelForm):
    38         class Meta:
    39         model = StudentModel
    40         fields = ('sname') #必须与model类的名字一样
    41 #简单HTML
    42 43     <form action="{% url 'django_test:hello' %}">
    44             {% for field in forms %}
    45                 {{ field.label_tag }}:{{ field }}
    46                 {{ field.errors }}
    47             {% endfor %}
    48             <input type="submit">
    49     </form>
    50 #Form实例属性
    51     
    52     {{ field.label_tag }} #表单元素标签
    53     {{ field }} #表单元素体
    54     {{ field.errors }} #表单元素错误
    55  
  • 相关阅读:
    python增加 删除列表元素
    Fildder2
    Appscan使用第三方浏览器
    Appscan的下载安装
    http状态码
    python学习资料
    Fiddler抓包工具
    性能测试的一些资料
    Jmeter分布式测试
    内存溢出的原因及解决办法(转)
  • 原文地址:https://www.cnblogs.com/SunQi-Tony/p/9229549.html
Copyright © 2011-2022 走看看