## 在網頁上做加減法
[demo下載][1]
### 1 采用 /add/?a=4&b=5 這樣GET方法進行
views.py
```python
from django.http import HttpResponse
def add(request):
a = request.GET.get('a', 0)
b = request.GET.get('a', 0)
c = int(a)+int(b)
return HttpResponse(str(c))
```
Django 1.7.x 及以下
urls.py
```python
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^add/$', 'learn.views.add', name='add'), # 注意修改了這一行
)
```
Django 1.8.x及以上,Django 官方鼓勵(或說要求)先引入,再使用。
urls.py
```python
from django.conf.urls import url
from learn import views as learn_views
urlpatterns = [
url(r'^add/$', learn_views.add, name='add'), # 注意修改了這一行
]
```
### 2 采用 /add/3/4/ 這樣的網址的方式
修改 calc/views.py文件,再新定義一個add2 函數
```python
def add(request, a, b):
c = int(a) + int(b)
return HttpResponse(str(c)
```
接著修改 urls.py 文件,再添加一個新的 url
#### 使用位置和分組進行賦值
Django 1.7.x 及以下:
```python
urlpatterns = [
url(r'^add/(?P<a>\d+)/(?P<b>\d+)/$', 'calc.views.add', name='add'),
url(r'^add/(\d+)/(\d+)/$', 'calc.views.add', name='add'),
]
```
Django 1.8.x 及以上, 視圖函數可以**不加引號**
```python
urlpatterns = [
url(r'^add/(?P<a>\d+)/(?P<b>\d+)/$', calc_views.add, name='add'),
url(r'^add/(\d+)/(\d+)/$', calc_views.add, name='add'),
]
```
### 3 采用 /add-3-4.html/ 這樣的網址的方式
```python
def add(request, a, b):
c = int(a) + int(b)
return HttpResponse(str(c)
```
Django 1.7.x 及以下:
```python
urlpatterns = [
url(r'^add(?P<a>\d+)-(?P<b>\d+).html/$', 'calc.views.add', name='add'),
url(r'^add(\d+)-(\d+).html/$', 'calc.views.add', name='add'),
]
```
Django 1.8.x 及以上, 視圖函數可以**不加引號**
```python
urlpatterns = [
url(r'^add(?P<a>\d+)-(?P<b>\d+).html/$', calc_views.add, name='add'),
url(r'^add(\d+)-(\d+).html/$', calc_views.add, name='add'),
]
```
## 數據提交
### 提交用戶名和密碼
后臺可以根據input標簽中的name獲取數據
#### templates
~~~
<form action="/login/" method="post">
<p>
<label for="username">用戶名:</label>
<input id="username" type="text" name="username" placeholder="用戶名"/>
</p>
<p>
<label for="password">密碼:</label>
<input id="password" type="password" name="password" placeholder="密碼"/> <br />
<input type="submit" value="提交" />
</p>
</form>
~~~
#### 網頁效果

#### 后臺數據處理
使用get獲取數據,并提供默認值,避免程序出錯
~~~
def login(request):
err_msg = ''
if request.method == 'POST':
username = request.POST.get('username', None)
password = request.POST.get('password', None)
if username == 'hiyang' and password == 'hiyang':
return redirect('/home/')
else:
err_msg = '密碼錯誤'
return render(request, 'login.html', {'err_msg': err_msg})
~~~
### 提交單選復選框
#### templates
~~~
<form action="postdata" method="POST">
{# 單選框 #}
<p>
<label for="favor">籃球</label><input type="radio" name="favor" value="lq">
<label for="favor">羽毛球</label><input type="radio" name="favor" value="ymq">
<label for="favor">乒乓球</label><input type="radio" name="favor" value="ppq">
<input type="submit" value="提交">
</p>
{# 復選框 #}
<p>
<label for="favor">籃球</label><input type="checkbox" name="favor" value="lq">
<label for="favor">羽毛球</label><input type="checkbox" name="favor" value="ymq">
<label for="favor">乒乓球</label><input type="checkbox" name="favor" value="ppq">
<input type="submit" value="提交">
</p>
</form>
~~~
#### 網頁效果

#### 后臺處理
~~~
def postdata(request):
if request.method == 'GET':
return render(request, 'post.html')
elif request.method == 'POST':
# radio 單選
print(request.POST.get('favor'))
# checkbox 多選,如果使用get只能獲取多個值中的最后一個
# print(request.POST.getlist('favor'))
return render(request, 'post.html')
else:
return HttpResponse('404')
~~~
### 提交單選和復選下拉框
#### templates
~~~
<form action="postdata" method="POST">
{# 單選和復選下拉框 #}
<p>
<select name="city" id="#" multiple>
<option value="sh">上海</option>
<option value="bj">北京</option>
<option value="nj">南京</option>
</select>
<input type="submit" value="提交">
</p>
</form>
~~~
#### 網頁效果

#### 后臺處理
~~~
def postdata(request):
if request.method == 'GET':
return render(request, 'post.html')
elif request.method == 'POST':
# select 單選
print(request.POST.get('city'))
# select 多選
# print(request.POST.getlist('city'))
return render(request, 'post.html')
else:
return HttpResponse('404')
~~~
### 上傳文件
#### templates
~~~
<form action="postdata" method="POST" enctype="multipart/form-data">
<p>
<input type="file" name="file">
<input type="submit" value="提交">
</p>
</form>
~~~
#### 網頁效果

#### 后臺處理
~~~
def postdata(request):
if request.method == 'GET':
return render(request, 'post.html')
elif request.method == 'POST':
# 獲取文件名
# print(request.POST.get('file'))
f_obj = request.FILES.get('file')
fd = open(f_obj.name, 'wb+')
# for chunks in f_obj.chunks(): # 遍歷chunk對象
for chunks in f_obj # 遍歷文件對象
fd.write(chunks)
fd.close()
return render(request, 'post.html')
else:
return HttpResponse('404')
~~~
>[info] 說明
文件對象 = reqeust.FILES.get()
文件對象.name
文件對象.size
文件對象.chunks()
### 其他參數
所有的請求參數都可以從`request.environ`獲得
比如`User-Agent`
~~~
request.environ['HTTP_USER_AGENT']
~~~
[1]:http://files.cnblogs.com/files/hiyang/demo_add_165.tar.gz
[2]:http://files.cnblogs.com/files/hiyang/demo_redirect_165.tar.gz