?
1. HttpRequest对象的信息
?
request.path 除域名以外的请求路径,斜杠开头 “/hello/”
request.get_host() 主机名 “127.0.0.1:8000” or “www.xxxx.com”
request.get_full_path() 请求路径,可能包含查询字符串 “/hello/?print=true”
request.is_secure() 是否通过Https访问 是为True,否为False
request.META 一个字典,包含本次Http请求的Header信息 例如 REMOTE_ADDR 表示客户端ip,
HTTP_USER_AGENT表示用户浏览器user-agent字符串
HTTP_REFERER表示进站前连接网页
request.POST 一个类字典对象保存html中
Please submit a search term.
{% endif %}?
?
其中action='' 表示表单将提交给与当前页面相同的URL
?
?
再添加search_results.html
?
?
You searched for: {{ query }}
{% if books %}Found {{ books|length }} book{{ books|pluralize }}.
- {% for book in books %}
- {{ book.title }}
- {% endfor %}
No books matched your search criteria.
{% endif %}?
在view.py中添加:
?
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)
return render_to_response('search_results.html',
{'books':books,'query':q})
return render_to_response('search_form.html',
{'error':error})
?
?
?
其中Book.objects.filter(title__icontains=q) 是用来获取数据库中标题包含q的书籍。icontains是一个查询关键字。
?
在urls.py 中添加
?
(r'search/$',search),
?
?
然后在浏览器输入 http://127.0.0.1:8000/search/ 可以看到一个简单的搜索界面。
?
3. 简单的验证
?
可以用Javascript在客户端浏览器进行验证,但可能有些人会将java script关闭,并且还有一些怀有恶意的用户会尝试提交非法的数据来探测是否有可以攻击的机会。所以除了用java script在客户端浏览器进行验证外,还需要在服务器验证一次。上面的代码,只对 输入为空做了验证。下面添加一个验证搜索关键字是否小于20个字符的验证。
?
例子:
修改view.py
?
def search(request):
errors = []
if 'q' in request.GET:
q = request.GET['q']
if not q:
errors.append('Enter a search term')
elif len(q) > 20:
errors.append('Please enter at most 20 characters.')
else:
books = Book.objects.filter(title__icontains=q)
return render_to_response('search_results.html',
{'books':books,'query':q})
return render_to_response('search_form.html',
{'errors':errors})
?
修改 search_form.html :
?
{{ error }}
{% endfor %} {% endif %}?
4. 编写Contact表单
?
?
一个较为复杂的例子:这个表单包括用户提交的反馈信息,一个可以选择填不填的e-mail地址。
?
view.py 中添加:
?
def contact(request):
errors = []
if request.method == 'POST':
if not request.POST.get('subject', ''):
errors.append('Enter a subject.')
if not request.POST.get('message', ''):
errors.append('Enter a message.')
if request.POST.get('email') and '@' not in request.POST['email']:
errors.append('Enter a valid e-mail address.')
if not errors:
send_mail(
request.POST['subject'],
request.POST['message'],
request.POST.get('email', 'noreply@example.com'),
['siteowner@example.com'],
)
return HttpResponseRedirect('/contact/thanks/')
return render_to_response('contact_form.html', {
'errors': errors,
'subject': request.POST.get('subject', ''),
'message': request.POST.get('message', ''),
'email': request.POST.get('email', ''),
},context_instance=RequestContext(request))
?
?
用POST不用GET,因为这个表单会有一个服务器端的操作:send_mail。