Django-表单

Django的forms解决了常规的表单验证问题

  • URL相关信息
    • request.path:除域名外的请求路径
    • request.get_host():主机名
    • request.get_full_path():请求路径,可能包括查询字符串
    • request.is_secure():是不是使用https安全访问
    • request.MATE是一个python字典,包含本次http请求的头信息,如试图访问不存在的键会触发KeyError错误
try:

except KeyError:

item():返回可遍历的(键,值)元组数组


提交的数据信息
httpRequest对象还有两个属性包含所提交的信息

  • request.GET
  • request.POST
    类字典对象(技术底层不是)
    request.GET和POST行为像python中的标准字典有get()、keys()、values()方法,可遍历for key in request.GET所有键

POST来自form标签指定,
GET来自form标签指定和查询字符串


表单实例(HTML表单)


contact表单:站点联系表单


Django的Form类
为每一个将要处理的HTML《Form》定义一个Form类

#forms.py
from django import forms

class addForm(forms.Form):
    subject = forms.CharField()
    email = forms.EmailField(required=False)
    message = forms.CharField()
#views.py
def index(request):
    if request.method == 'POST':
        form = addForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data['subject']
            return render(request,'myblogs/index.html',{'form':form,'cd':cd})
    else:
        form = addForm()
    return render(request,'myblogs/index.html',{'form':form})

#html
"" method="post"> {% csrf_token %} {{form}} type="submit" value="queren">
{{cd}}

表单的每一个字段域作为Form类的一个属性,每一个字段都默认必填
,可选项required = False
调用form的is_valid检测合法性。如果数据合法,它有一个可用的cleaned_data,这是一个包含干净的提交数据的字典。
每一个Form实体都有一个error属性,它为你提供一个字段与错误消息相映射的字典表


forms框架把每一个字段的显示逻辑分离到widget中,Field校验逻辑

message = forms.CharField(widget=forms.Textarea)

设置最大长度

subject = forms.CharField(max_length=100)
最小的依然成立

设置初始值
使用initial

def index(request):
    if request.method == 'POST':
        form = addForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data['subject']
            return render(request,'myblogs/index.html',{'form':form,'cd':cd})
    else:
        form = addForm(initial={'subject':'haha'})
    return render(request,'myblogs/index.html',{'form':form})

自定义校验规则(大多一次性,可直接绑定到form)
如message最起码4个字
校验规则是在点击提交后开始运行

这里写代码片

定制标签

subject = forms.CharField(label='You')

定制Form设计
form.as_ul 和form.as_table
自动生成的错误列表精确使用《ul class=“errorlist”
每一个字段部件都可以通过访问{{form.字段名}}进行单独渲染
input 的id为id_字段名


<html>
<head>
    <meta charset="utf-8">
    <title>我的boketitle>
head>
<style>
/**改subject的input css**/
#id_subject{border:1px red solid;}
style>
<body>

<form action="" method="post">
    <div class="field1">
        {{ form.subject.errors }}
        <label for="id_subject">Subject:label>
        {{ form.subject }}
    div>
    /***改email的label***/
    <label style="color: red;" for="id_email">Your e-mail address:label>

    <input type="submit" value="Submit">
form>

<p color="red">{{cd}}p>

body>
html>

django表单的其他字段

#forms.py利用model创建表单
from django import forms
from .models import *
class AddForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['name', 'price', 'number', 'image']

#url
    url(r'^publishgoods/$',views.publishgoods,name='publishgoods'),
url(r'^pgr/$',views.pgr,name='pgr'),


#views
#显示表单
def publishgoods(request):
    uid = request.session.get('uid')
    user = Duser.objects.get(id=uid)
    form = AddForm()
    return render(request,'dweb/publishgoods.html',{'form': form,'user':user})

#表单结果提交页面
def pgr(request):
    uid = request.session.get('uid')
    user = Duser.objects.get(id=uid)
    if request.method == 'POST':# 当提交表单时
        form = AddForm(request.POST or None, request.FILES) # form 包含提交的数据
        if form.is_valid():# 如果提交的数据合法
            name = form.cleaned_data['name']
            price = form.cleaned_data['price']
            image = form.cleaned_data['image']
            number = form.cleaned_data['number']
            product = Product.objects.create(name=name,price=price,image=image,number=number)
            id = product.id
            Publishgoods.objects.create(userid=Duser.objects.get(id=uid),           productid=Product.objects.get(id=id),number=number)
            pgr = Publishgoods.objects.all().filter(userid=uid)
            return render(request,'dweb/pgr.html',{'user':user,'pgr':pgr})
    pgr = Publishgoods.objects.all().filter(userid=uid)
    return render(request,'dweb/pgr.html',{'user':user,'pgr':pgr})

你可能感兴趣的:(Django)