django-表单

一、从Request对象中获取信息

1、URL相关的信息

属性/方法 说明 举例
request.path 除域名以外的请求路径,以正斜杠开头 “/hello/”
request.get_host() 主机名(通常所说的域名)

“127.0.0.1:8000”

“www.example.com”

request.get_full_path() 请求路径,可能包含查询字符串 “/hello/?print=true”
request.is_secure() 如果通过HTTPS访问,则此方法返回true,否则返回false TRUE或者false

2、其他信息:

(1)request.META:包含本次所有HTTP请求的Header信息(如用户IP地址,用户Agent(通常是浏览器名称和版本号))

常见的键值:HTTP_REFERER:进站前链接网页;

      HTTP_USER_AGENT:浏览器的user-agent字符串;

      REMONT_ADDR:客户端IP;

3、下来我们来创建一个简单的表单:

#views.py
def search_form(request):
    return  render_to_response('search_form.html')

def search(request):
if 'q' in request.GET:
message = '您搜索了 :%r'% request.GET['q']
else:
message = '你提交了一个空表单'  #如果不进行判断,如果提交空表单就会出错
return HttpResponse(message)
#search_form.html
<form action="/search/" method="get">
    <input type="text" name="q"/>
    <input type="submit" value="search">
</form>
 url(r'^search-form/$',views.search_form),
 url(r'^search/$',views.search),

    

4、测试完成之后来实现书籍的查询;

def search(request):
    error = False
    if 'q' in request.GET:
        q = request.GET['q']
        if not q:
            error = True
        else:
            books = Book.objects.filter(title__icontains = q)   #__icontains查询关键字:模糊匹配,不区分大小写
            return render_to_response('search_results.html',
                                  {'books':books,'query':q})
    return render_to_response('search_form.html',
                                  {'error':error})
<body>
{% if error %}
<p style="color:red">please submit a search term</p>
{% endif %}
<form action="" method="get">
    <input type="text" name="q"/>
    <input type="submit" value="search">
</form>
</body>
<body>
<p>you searched for:<strong>{{ query }}</strong></p>

{% if books %}
<p>Found {{ books|length }}book{{ books|pluralize }}.</p>  <!--单词的复数形式,如列表字符串个数大于1,返回s,否则返回空串-->
<ul> 
{
% for book in books %}
  <li>{{ book.title }} : {{ book.publisher }}</li>
{
% endfor %}
</ul>
{
% else %}
<p>No books matched your search criteria</p>
{
% endif %}
</body>

 访问127.0.0.1:60500/search-form/,如图一,若提交空表单,显示如图二;查询“python”关键字得到图三:

    

5、接下来我们队用户的输入进行一个简单的验证(不超多20个字符):

def search(request):
    errors = []
    if 'q' in request.GET:
        q = request.GET['q']
        if not q:
            errors.append('please submit a search term')
        elif len(q) > 20:
            errors.append('please enter at most 20 charactors')
        else:
            books = Book.objects.filter(title__icontains = q)   #__icontains查询关键字:模糊匹配,不区分大小写
            return render_to_response('search_results.html',
                                  {'books':books,'query':q})
    return render_to_response('search_form.html',
                                  {'errors':errors})
#search_form.html
<body>
{% if errors %}
<ul>
    {% for error in errors %}
    <li>{{ error }}</li>
    {% endfor %}
</ul>
{% endif %}
<form action="" method="get">
    <input type="text" name="q"/>
    <input type="submit" value="search">
</form>
</body>

      提交空表单                              关键字超过20个字符                                  正常提交

    

6、体验站点联系表单:

我们想要创建一个表单含有三个字段:subject,message和email

 (1)先 在firstSite目录下(books的同级目录)新建一个app,使用命令:python manage.py startapp contact,然后再contact目录下新建一个名为forms.py的文件,在这个文件里面创建我们的Form类。

  django带有一个form库成为django.forms,这个库可以处理表单HTML的显示和验证;

#    -*- coding:utf-8 -*-
from django import forms    #引入form库

class ContactForm(forms.Form):
    subject = forms.CharField(max_length= 100)  #设置最大值
    email = forms.EmailField(required= False,label= 'Your e-mail address')   #email为非必填选项
    message = forms.CharField(widget= forms.Textarea)  #设置HTML里面message的标签为textarea,而不是input type=‘text’

 (2)在我们的views.py文件中:

#    -*- coding:utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.mail import send_mail
from contact.forms import ContactForm
from django.template import RequestContext
# Create your tests here.
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():     #检验输入数据是否合法
            cd = form.cleanded_data     #清理数据
            send_mail(      #发送邮件函数,四个必选参数:(主题,正文,寄信人,收件人)
                cd['subject'],
                cd['message'],
                cd.get('email', 'noreply@example.com'),
                       ['siteowner@example.com'],
            )
            return  HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm(
            initial= {'subject': "it's nice"}  #设置初始值
        )
    return render_to_response('contact_form.html',
                              {'form':form},
     ) 

 (3)在我们的Contact.html里: 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>contact_form</title>
</head>
<body>
<h1>Contact us</h1>
{% if form.errors %}    <!--内置errors字典-->
<p style="color:red">
    Please corrent the error{{ form.errors|pluralize }} below
</p>
{% endif %}

<form action="" method="post">
    <table>
       {{ form.as_table }}      <!--按照<table>输出,还有其他形式的输出:form.as_ul(),form.as_p-->
    </table>
    <input type="submit" value="submit"/>
</form>
</body>
</html>

 (4)接下来我们如果要自定义一些验证方式(比如说message字段不可以少于4个)可以在ContactForm类中定义函数:

#    -*- coding:utf-8 -*-
from django import forms    #引入form库

class ContactForm(forms.Form):
    subject = forms.CharField(max_length= 100)
    email = forms.EmailField(required= False,label= 'Your e-mail address')   #email为非必填选项,自定义标签
    message = forms.CharField(widget= forms.Textarea)  #改变html显示

    def clean_message(self):    #命名规范:名称以clean_开头,以字段名称结束;
        message = self.cleaned_data['message']
        num_words = len(message.split())
        if num_words < 4:
            raise forms.ValidationError('not enough words!')    #如果不足,抛出异常
        return message

(5)接下来我们来配置url,在firstSite目录下的urls配置:

#    -*- coding:utf-8 -*-
from django.conf.urls import url    #导入 django.conf.urls 模块下的url类
from django.contrib import admin
from django.conf.urls import url,include
admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^books/',include('books.urls')),
    url(r'^contact/',include('contact.urls')),
]

(6)在Contact目录下的urls中配置:

#    -*- coding:utf-8 -*-from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^contact/$',views.contact),
]

(7)我们对其进行访问: 

     

(7)如果你得到如下报错页面,

可以按照以下步骤解决:

(8)自动显示HTML是很方便的,但是我们在需要的时候也可以重写默认显示;{{ form.as_table}}和其他的方法可以帮你这个忙;每一个字段部件(input type='text',<select>,<textarea>等)都可以通过访问{{form.字段名}}进行单独的渲染;

<form action="" method="post" class="form_1">{% csrf_token %}
    <div class="field">
        {{ form.subject.errors }}
        <label class="left" for="id_message">Subject:</label>
        {{ form.subject }}
    </div>
    <div class="field">
        {{ form.email.errors }}
        <label class="left" for="id_message">Your e-mail address:</label>
        {{ form.email }}
    </div>
    <div class="field">
        {{ form.message.errors }}
        <label class="left_last" for="id_message">Message:</label>
        {{ form.message }}
    </div>
    <!--<table>-->
       <!--{{ form.as_table }}      &lt;!&ndash;按照<table>输出,还有其他形式的输出:form.as_ul(),form.as_p&ndash;&gt;-->
    <!--</table>-->
    <input class="submit" type="submit" value="submit"/>
</form>

 

posted on 2017-12-13 16:21 cencenyue 阅读(...) 评论(...) 编辑 收藏

统计