本文共 4918 字,大约阅读时间需要 16 分钟。
在本节前介绍个字典的get方法: get(key,default=None) 返回键值key对应的值;如果key没有在字典里,则返回default参数的值,默认为None1.Information About the request
reqeust作用网站的关键骨干之一,有着举足轻重的地位。 详细情况可以参照django.http.__init__.py文件中的定义。 以下列举几个例子: 1)request.path ------/hello/ 2)request.get_host()-----127.0.0.1:8080 or 3)request.get_full_path()--/hello/?print=True 4)request.is_secure() -(HTTPS) True,False2.Request变量 self.GET,
self.POST, self.COOKIES, self.FILES = {}, {}, {}, {}, {} self.path self.path_info self.method self.META:1)self.META
主要是包含一些HTTP headers HTTP_REFERER URL数据,HTTP_USER_AGENT客户端浏览器信息。REMOTE_ADDR用户IP 注意这些信息是由客户端浏览器提交的,所以很可能一些值是没有的。如果要访问的值 没有则会抛出异常,所以子啊用META时要自己处理好异常。例: def ua_display_good1(request): try: ua = request.META['HTTP_USER_AGENT'] except KeyError: ua = 'unknown' return HttpResponse("Your browser is %s" % ua) 当然更好的方法是用get函数来处理 def ua_display_good2(request): ua = request.META.get('HTTP_USER_AGENT', 'unknown') return HttpResponse("Your browser is %s" % ua)2)self.GET,self.POST
这两个属性太熟悉了,他们是类似字典但比字典要强大的两个属性。3.Form class
1)像Models可以定义类一样,Form表单也可以这样定义的。通常情况下,咱们 把form放在app中的forms.py文件中。form例子如下: from django import formsclass ContactFrom(forms.Form):
subject = forms.CharField() email = forms.EmailField(required=False) message = forms.CharFiled() 这段代码等效的html代码如下: >>> from contact.forms import ContactForm >>> f = ContactForm() >>> print f <tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" id="id_subject" /></td></tr> <tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr> <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>2)可见,Form的默认输出方式为表格。Django中有很多种内建输出方式。
例如:print f.as_ul()就会以列表的形式输出。 3)访问单个域,例如只访问subject,代码f['subject']等效于: <input type = "text" name="subject" id="id_subject"/>4)可以通过is_valid()函数来判断表单数据提交的是否正确。
例如,由于email选项我们有required=False选项,所以该项不赋值,函数验证也是正确的。 >>> f = ContactForm({'subject': 'Hello', 'message': 'Nice site!'}) >>> f.is_valid() True 一旦创建了一个绑定的表单,则表单的bound属性即为True,即f.is_bound = True 相反,如果该提交的数据没有提交,则会自动生成错误。 >>> f = ContactForm({'subject': 'Hello', 'message': ''}) >>> f['message'].errors [u'This field is required.'] >>> f['subject'].errors [] >>> f['email'].errors []**每个绑定的表单实例都会有一个filed name和error message构成的字典。
这样可以很轻松的用来提示用户的输入错误。 5)cleaned_data,如下图所示,cleaned_data属性,可以将valid的数据转换为 在定义form时的对应的python类型,比如定义时时IntegerField,则会将对应的值转换为int >>> f = ContactForm({‘subject’: ‘Hello’, ‘email’: , ‘message’: ‘Nice site!’}) >>> f.is_valid() True >>> f.cleaned_data {‘message’: u’Nice site!’, ‘email’: , ‘subject’ 6)完整的例子: # views.pyfrom django.shortcuts import render_to_response
from mysite.contact.forms import ContactFormdef contact(request):
if request.method == 'POST': form = ContactForm(request.POST)#这里如果用户提交错误,则form中就会 #包含错误信息,在render时就能在提交错误的字段中提示错误信息。 if form.is_valid(): cd = form.cleaned_data send_mail( cd['subject'], cd['message'], cd.get('email', ), ['siteowner@example.com'], ) return HttpResponseRedirect('/contact/thanks/') else: form = ContactForm() return render_to_response('contact_form.html', {'form': form})# contact_form.html
<html>
<head> <title>Contact us</title> </head> <body> <h1>Contact us</h1>{% if form.errors %}
<p style="color: red;"> Please correct the error{ { form.errors|pluralize }} below. </p> {% endif %}<form action="" method="post">
<table> { { form.as_table }} </table> <input type="submit" value="Submit"> </form> </body> </html>4.定制表单 每种字段都有默认的表示形式,当然可以定制自己想要的表现形式。
1)表单属性 from django import formsclass ContactForm(forms.Form):
subject = forms.CharField(max_length=100,min_length=10) email = forms.EmailField(required=False) message = forms.CharField(widget=forms.Textarea)#######2)表单默认值
form = ContactFrom( inital={"subject":'I love your site'} ) 3)定制验证规则 from django import forms class ContactForm(forms.Form): subject = forms.CharField(min_length=10) email = forms.emailField(required=False) message = forms.CharField(widget=forms.Textare) def clean_message(self):#需要验证的函数名第一个是clean_,最后一个是字段名。 #自己定义的验证消息,只有在通过默认的验证后 message = self.cleand_data['message']#自己定义的验证只是在默认验证基础上增加了东西。 num_words = len(message.split()) if num_words < 4: raise forms.ValidationError('not enougth words!') return message#则条语句千万不能忘掉,否则即使验证OK了,却返回了None 4)制定label名称 同models的verbose_name一样,Form也可以指定自己的label名字 from django import forms class ContactForm(forms.Form): subject = forms.CharField(min_length=10,label = 'your subject') email = forms.emailField(required=False, label = 'your email') message = forms.CharField(widget=forms.Textare) 5)表单格式 可以很轻松的通过CSS对表单样式进行修改,例如表单填写错误时显示修改errorlist <style type="text/css"> ul.errorlist { margin: 0; padding: 0; } .errorlist li { background-color: red; color: white; display: block; font-size: 10px; margin: 0 0 3px; padding: 4px 5px; } </style>同样由于每个表单字段都可以通过{
{ form.fieldname }} 来访问,每个字段的错误 都可以通过{ { form.fieldname.errors }}. 来访问,所以可以根据需要进行强大的定制。 <本节完> 原文网址:转载地址:http://nzxci.baihongyu.com/