在以前hello python的例子中:
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello python")
HttpRequest有一些參數和屬性咱們須要瞭解下,包括URL相關信息(如請求路徑、主機地址、是否經過https訪問)、request.META字典集合(用戶ip地址、瀏覽器名稱版本號等),
還有一個就是咱們今天要了解的request.GET和request.POST類字典對象,分別對應於表單提交的GET和POST方法。
下面來看個例子:
search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
# urls.py
urlpatterns = patterns('',
(r'^search‐form/$', views.search_form),
(r'^search/$', views.search),
在view的search方法中獲取表單提交的值:
# views.py
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You submitted an empty form.'
return HttpResponse(message)
改進表單:
一、填寫錯誤應不作表單跳轉;
二、數據合法性判斷在客戶端作;
針對上面可改進以下:
#view.py
def search(request):
if 'q' in request.GET:
q = request.GET['q']
if not q:
error = 'xx不能爲空'
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}
#search-form.html
<html>
<head>
<title>Search</title>
<script>
function check(){
value_username=document.getElementById("id_username").value;
if(value_username.trim().length<1){
alert("用戶名不能爲空!");
}
}
</script>
</head>
<body>
{ if error %}
<p style="color: red;">{{error}}</p>
{% endif %}
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search" onClick="check()">
</form>
</body>
</html>
下面看看post傳值:
相應的改爲
if request.method == 'POST':
if not request.POST.get('subject', ''):
errors = '數據不能爲空'
以上例子都是用原生html寫表單的,django所以本身封裝了一套表單模型,來看看:
Django帶有一個form庫,稱爲django.forms,這個庫能夠處理咱們本章所提到的包括HTML表單顯示以及驗證。
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField()
email = forms.EmailField(required=False)
message = forms.CharField()
python解釋器會解析爲
<tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" id="id_subject...
<tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email"...
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message...
下面咱們結合今天所講的來作個簡單的用戶註冊例子:
個人博客其餘文章列表
http://my.oschina.net/helu