1、Django 學習— 表單get和post
1.1 get 方法
- Django的get 後台處理(t1.py)
from django.http import HttpResponse
from django.shortcuts import render
# 表單
def search_form(request):
return render(request, 'x1.html')
# 接收請求數據
def search(request):
request.encoding = 'utf-8'
if 'q' in request.GET and request.GET['q']:
message = '你搜索的內容為: ' + request.GET['q']
else:
message = '你提交了空表單'
return HttpResponse(message)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>get方法</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="搜索">
</form>
</body>
</html>
1.2 post 方法
from django.shortcuts import render
from django.views.decorators import csrf
# 接收POST請求數據
def search_post(request):
ctx = {
}
if request.POST:
ctx['rlt'] = request.POST['q']
return render(request, "x2.html", ctx)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>post方法</title>
</head>
<body>
<form action="/search-post/" method="post">
{% csrf_token %}
<input type="text" name="q">
<input type="submit" value="搜索">
</form>
<p>{
{ rlt }}</p>
</body>
</html>