码迷,mamicode.com
首页 > 其他好文 > 详细

form 组件

时间:2018-04-02 16:03:49      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:forms   下划线   ack   nova   ice   choice   生成   **kwargs   不能   

  • 初始form组件

 

  Django的Form主要具有一下几大功能:

 

  •   生成HTML标签
  •   验证用户数据(显示错误信息)
  •   HTML Form提交保留上次提交数据
  •   初始化页面显示内容

 

  1. 验证功能
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post" action="/form/">
        <P><input type="text" name="username">{{ obj.errors.username.0 }}</P>
        <P><input type="password" name="pwd">{{ obj.errors.pwd.0 }}</P>
        <P><input type="text" name="age">{{ obj.errors.age.0 }}</P>
        <P><input type="text" name="email">{{ obj.errors.email.0 }}</P>
        <p><input type="submit"></p>
    </form>

</body>
</html>
from django import forms
from django.forms import fields


class RegisterForm(forms.Form):
    username = forms.CharField(max_length=20, min_length=6, required=True,
                               error_messages={
                                   required:用户名不能为空,
                                   max_length: 最大长度20,
                                    min_length: 最小长度6,
                               })
    pwd = forms.CharField(max_length=20, min_length=6, required=True)
    age = forms.IntegerField(required=True)
    email = forms.EmailField(required=True,error_messages={
        invalid:格式错误
    })
from django.shortcuts import render
from myform.cfrom import RegisterForm
# Create your views here.


def form(request):
    if request.method == GET:
        return render(request, forms/index.html)
    else:
        print(request.POST)
        obj = RegisterForm(request.POST)
        if obj.is_valid():
            print(obj.cleaned_data)
        else:
            print(obj.errors)
    return render(request, forms/index.html,{obj:obj})
  1. 生成input标签功能
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post" action="/form/" novalidate>
        <P>{{ form_obj.username }}{{ form_obj.errors.username.0 }}</P>
        <P>{{ form_obj.pwd }}{{ form_obj.errors.pwd.0 }}</P>
        <P>{{ form_obj.age }}{{ form_obj.errors.age.0 }}</P>
        <P>{{ form_obj.email }}{{ form_obj.errors.email.0 }}</P>
        <p><input type="submit"></p>
    </form>

</body>
</html>
from django.shortcuts import render
from myform.cfrom import RegisterForm
# Create your views here.


def form(request):
    if request.method == ‘GET‘:
        form_obj = RegisterForm()
        return render(request, ‘forms/index.html‘, {‘form_obj‘: form_obj})
    else:
        print(request.POST)
        form_obj = RegisterForm(request.POST)
        # obj = RegisterForm(request.POST)
        if form_obj.is_valid():
            print(form_obj.cleaned_data)
        else:
            print(form_obj.errors)
    return render(request, ‘forms/index.html‘, { ‘form_obj‘: form_obj})

 form类

from django import forms
from django.forms import fields
from django.forms import widgets


class RegisterForm(forms.Form):
    username = fields.CharField(
        max_length=20,
        min_length=6,
        required=True,
        widget=widgets.TextInput(attrs={v: v1, class: c1}),
        initial=用户名,
        label=用户名,
        help_text=字母、数字、下划线,
        disabled=False,
        label_suffix=:,
        error_messages={
            required: 用户名不能为空,
            max_length: 最大长度20,
            min_length: 最小长度6,
        },
    )
    pwd = fields.CharField(
        max_length=20,
        min_length=6,
        required=True,
        label=密码,
        widget=widgets.PasswordInput
    )
    age = fields.IntegerField(
        required=True,
        max_value=200,
        min_value=0,
        label=年龄,
    )
    email = fields.EmailField(required=True, error_messages={
        invalid: 格式错误
    },
                              label=邮箱,
                              )
    # 单选select
    city = fields.ChoiceField(
        choices=[
            (1, 中国),
            (2, 美国),
            (3, 日本),
        ],
        initial=1,
        label=国籍,
    )
    # 多选select
    hobby = fields.MultipleChoiceField(
        choices=[
            (1, 音乐),
            (2, 把妹),
            (3, 约妹),
        ],
        initial=[1, 3]
    )

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)  # 必须在self.fieLds上面
        self.fields[hobby].widget.choices = ((1, ), (2, 嗨嗨),)
        #
        # self.fields[‘hobby‘].widget.choices = models.Classes.objects.all().value_list(‘id‘, ‘caption‘)

    # 文件
    img = fields.FileField(
        label=图片
    )

    # 单选的checkbox
    chk = fields.CharField(
        widget=widgets.CheckboxInput(
            attrs={v: v1, class: c1}
        ),
        label=居住地
    )

    # 多选checkbox,值为列表
    dchk = fields.MultipleChoiceField(
        initial=[2, 1],
        choices=((1, 上海),
                 (2, 北京),),
        widget=widgets.CheckboxSelectMultiple,
        label=曾住地
    )

    # 单选的radio
    rad = fields.CharField(
        widget=widgets.RadioSelect(choices=((1, ), (2, ),)),
        label=性别
    )

    # 单radio,值为字符串
    rad1 = fields.ChoiceField(
        choices=((1, ), (2, ),),
        initial=2,
        widget=widgets.RadioSelect(
            attrs={class: ll}
        ),
        label=媳妇
    )

 技术分享图片

form 组件

标签:forms   下划线   ack   nova   ice   choice   生成   **kwargs   不能   

原文地址:https://www.cnblogs.com/liyqiang/p/8689107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!