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

Django的Form

时间:2017-11-14 14:44:42      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:validate   htm   ken   status   使用   python   字典   ror   号码   

Django的Form有两个基本用途:

  1、用于生成html的Form表单

  2、用于后台做表单验证

  

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
from django import forms
from django.core.exceptions import ValidationError


def mobile_validate(value):
    mobile_re = re.compile(r^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$)
    if not mobile_re.match(value):
        raise ValidationError(手机号码格式错误)


class PublishForm(forms.Form):

    user_type_choice = (
        (0, u普通用户),
        (1, u高级用户),
    )

    user_type = forms.IntegerField(widget=forms.widgets.Select(choices=user_type_choice,
                                                                  attrs={class: "form-control"}))

    title = forms.CharField(max_length=20,
                            min_length=5,
                            error_messages={required: u标题不能为空,
                                            min_length: u标题最少为5个字符,
                                            max_length: u标题最多为20个字符},
                            widget=forms.TextInput(attrs={class: "form-control",
                                                          placeholder: u标题5-20个字符}))

    memo = forms.CharField(required=False,
                           max_length=256,
                           widget=forms.widgets.Textarea(attrs={class: "form-control no-radius", placeholder: u详细描述, rows: 3}))

    phone = forms.CharField(validators=[mobile_validate, ],
                            error_messages={required: u手机不能为空},
                            widget=forms.TextInput(attrs={class: "form-control",
                                                          placeholder: u手机号码}))

    email = forms.EmailField(required=False,
                            error_messages={required: u邮箱不能为空,invalid: u邮箱格式错误},
                            widget=forms.TextInput(attrs={class: "form-control", placeholder: u邮箱}))
#试图函数中做验证
def publish(request):
    ret = {status: False, data: ‘‘, error: ‘‘, summary: ‘‘}
    if request.method == POST:
        request_form = PublishForm(request.POST)
        if request_form.is_valid():    #验证form,返回false和true
            request_dict = request_form.clean()  #返回字典类型的form信息
            print request_dict
            ret[status] = True
        else:
            error_msg = request_form.errors.as_json() #返回json格式的错误信息
            ret[error] = json.loads(error_msg)
    return HttpResponse(json.dumps(ret))

生成html

需要用到模板语言来渲染

<form action="/" method="POST" enctype="multipart/form-data">
    <p>{{ form.user }} {{ form.user.errors }}</p>
    <p>{{ form.gender }} {{ form.gender.errors }}</p>
    <p>{{ form.city }} {{ form.city.errors }}</p>
    <p>{{ form.pwd }} {{ form.pwd.errors }}</p>
    <input type="submit"/>
</form>
 <form method="POST" enctype="multipart/form-data">
        {% csrf_token %} <--!用于跨站请求伪造的!-->
        
            {{ form.xxoo.label }}
            {{ form.xxoo.id_for_label }}
            {{ form.xxoo.label_tag }}
            {{ form.xxoo.errors }}
            <p>{{ form.user }} {{ form.user.errors }}</p>
            <input type="submit" />
    </form>

 

ModelForm:

  用来做admin的form验证

在使用Model和Form时,都需要对字段进行定义并指定类型,通过ModelForm则可以省去From中字段的定义

class AdminModelForm(forms.ModelForm):
      
    class Meta:
        model = models.Admin
        #fields = ‘__all__‘
        fields = (username, email)
          
        widgets = {
            email : forms.PasswordInput(attrs={class:"email"}),
        }

 

Django的Form

标签:validate   htm   ken   status   使用   python   字典   ror   号码   

原文地址:http://www.cnblogs.com/zuoshoushizi/p/7831518.html

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