解決django中form表單設置action后無法回到原頁面的問題
django中form表單設置action后,點提交按鈕是跳轉到action頁面的,比如設置action為login,網(wǎng)址為192.168.1.128,跳轉后便會來到192.168.1.128/login,F(xiàn)5刷新也會是重新提交表單對話框,無法回到原頁面。
因此就要在django服務器進行重定向,具體就是
from django.shortcuts import redirect #最后返回原頁面 return redirect(url)
補充知識:Django + Ajax發(fā)送POST表單,并將返回信息回顯到頁面中
將表單數(shù)據(jù)發(fā)送回后端,然后處理后端返回的信息并顯示在當前頁面中,這里使用Ajax進行處理;
那么先看js代碼:
<!--以下為 Ajax腳本 -->
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#save").click(function(){
$.ajax({
url:"/api/add_event/", #url
type: "POST", #提交表單的類型,相當于method="post"
dataType: "json", #dataType, 這個是請求后,返回的數(shù)據(jù)將以json格式顯示
data:{"name": $("#id_name").val(), #在"#"號后面是控件id, 所以千萬不要搞錯了,要不然會出大事的
"limit":$("#id_limit").val(),
"address": $("#id_address").val(),
"start_time": $("#id_start_time").val(),
"status": $("#id_status").val(),
}, #Data這個地方,必須要獲取數(shù)據(jù),代表將獲取到的數(shù)據(jù)發(fā)送到后端,后端再進行處理
success:function(data){
console.log(data); #調(diào)試使用
console.log(data.status); #調(diào)試使用
console.log(data.message); #調(diào)試使用
$(".text").text(data.message); #將后端返回到結果通過前端頁面進行展示
}, #注意標點
}); #需要注意標點符號,如果標點符合錯誤了,那ajax基本上都不會執(zhí)行(否則,后果很嚴重哦)
}); #注意標點
}); #注意標點
</script>
注意(踩過的坑):
1.contentType: "application/json" ——>加入該語句時,在后端print(request.POST)時無法獲取內(nèi)容,相當于后端根本拿不到數(shù)據(jù)。因此在網(wǎng)上搜索了解到,使用contentType: “application/json”則data只能是json字符串;不使用時contentType一般為默認的application/x-www-form-urlencoded格式, 因此如果不限制 POST格式,干脆就不寫。
2. 說說“data”這里面需要注意:data:{"name", $("#id_name").val(), } 這其中id_name必須為控件的id 名稱,使用其它的則不能獲取的數(shù)據(jù),這個還是得注意。
3. 標注符號,標點符號,標點符號,重要的事情說三遍,當然可以借助專門的編輯器(我主要是懶哦,哈哈)
4. $(".text").text(data.message); 回顯在html中,是對后端返回的數(shù)據(jù)進行處理
那行回顯在網(wǎng)頁面上面
<font color="red"> <span class="text"></span> </font>
以下為html代碼
<div class="container">
<div class="col-md-4 col-md-offset-4">
<form id="form1" onsubmit="return false" action="##" method="POST" class="form-horizontal">
<!--此處就是通過后端返回到前端,前端進行展示-->
<font color="red">
<span class="text"></span>
</font>
<div class="form-group">
<label for="id_name">發(fā)布會名稱:</label>
<input type="text" name="name" class="form-control" placeholder="發(fā)布會名稱" maxlength="128" required id="id_name" />
</div>
<div class="form-group">
<label for="id_limit">Limit:</label>
<input type="number" name="limit" class="form-control" required id="id_limit" />
</div>
<div class="form-group">
<label for="id_address">發(fā)布會地址:</label>
<input type="text" name="address" class="form-control" placeholder="地址" maxlength="128" required id="id_address" />
</div>
<div class="form-group">
<label for="id_start_time">開始日期:</label>
<input type="text" name="start_time" required id="id_start_time" />
</div>
<div class="form-group">
<label for="id_status">發(fā)布狀態(tài):</label>
<select name="status" id="id_status">
<option value="blank">-----</option>
<option value="1">True</option>
<option value="0">False</option>
</select>
</div>
<div align="center">
<input class="btn btn-lg btn-primary" id="save" type="submit" value="保存發(fā)布會" ></input >
</div>
</form>
</div>
</div>
現(xiàn)在來看一下后端的代碼:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def add_event(request):
if request.is_ajax():
print(request.body)
print(request.POST)
name = request.POST.get('name', '') # 發(fā)布會名稱
limit = request.POST.get('limit', '') # 限制人員
status = request.POST.get('status', '') # 發(fā)布會狀態(tài)
address = request.POST.get('address', '') # 發(fā)布會地址
start_time = request.POST.get('start_time', '') # 發(fā)布會時間
if name == '' or limit == '' or status == '' or start_time == '':
return JsonResponse({'status': 10021, 'message': 'parameter error'})
# 判斷發(fā)布會名稱重復
result = Event.objects.filter(name=name)
if result:
return JsonResponse({'status': 10023, 'message': 'event name already exists'})
if status == '':
status = 1
try:
# Event.objects.create(id = eid, name = name, limit = limit, address = address, status = int(status), start_time=start_time)
Event.objects.create(name=name, limit=limit, address=address, status=int(status), start_time=start_time)
except ValidationError as e:
error = 'start_time format error. It must be in YYYY-MM-DD HH:MM:SS'
return JsonResponse({'status': 10024, 'message': error})
return JsonResponse({'status': 200, 'message': 'add event success'})
1、在后端處理時,我們需要加入:@csrf_exempt 標記,所以導包from django.views.decorators.csrf import csrf_exempt,否則會出現(xiàn)錯誤csrf_token錯誤 (403)
2、request.is_ajax()判斷當前是否是使用ajax 進行表單提交
3、django request.POST / request.body
當request.POST沒有值 需要考慮:
1.請求頭中的: Content-Type: application/x-www-form-urlencoded request.POST中才會有值(才會去request.body中解析數(shù)據(jù)),關于Content-Type前面也提到,不寫的錯誤,它就是默認。
request.body的請求數(shù)據(jù)
b'name=%E5%A4%BA%E5%A4%BA&limit=123‘
request.POST的數(shù)據(jù),django已進行自動處理
QueryDict: {‘name': [‘奪奪'], ‘limit': [‘123']
以上這篇解決django中form表單設置action后無法回到原頁面的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- Django表單外鍵選項初始化的問題及解決方法
- django表單中的按鈕獲取數(shù)據(jù)的實例分析
- Django def clean()函數(shù)對表單中的數(shù)據(jù)進行驗證操作
- Django 構建模板form表單的兩種方法
- Django form表單與請求的生命周期步驟詳解
- Django model.py表單設置默認值允許為空的操作
- Django表單提交后實現(xiàn)獲取相同name的不同value值
- Django框架獲取form表單數(shù)據(jù)方式總結
- django之從html頁面表單獲取輸入的數(shù)據(jù)實例
- django-xadmin根據(jù)當前登錄用戶動態(tài)設置表單字段默認值方式
- Django給表單添加honeypot驗證增加安全性
相關文章
Python中threading.Timer()定時器實現(xiàn)定時任務
本文主要介紹了Python中threading.Timer()定時器實現(xiàn)定時任務,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-01-01
Python機器學習pytorch模型選擇及欠擬合和過擬合詳解
如何發(fā)現(xiàn)可以泛化的模式是機器學習的根本問題,將模型在訓練數(shù)據(jù)上過擬合得比潛在分布中更接近的現(xiàn)象稱為過擬合,用于對抗過擬合的技術稱為正則化2021-10-10
Python 網(wǎng)絡編程之TCP客戶端/服務端功能示例【基于socket套接字】
這篇文章主要介紹了Python 網(wǎng)絡編程之TCP客戶端/服務端功能,結合實例形式分析了Python使用socket套接字實現(xiàn)TCP協(xié)議下的客戶端與服務器端數(shù)據(jù)傳輸操作技巧,需要的朋友可以參考下2019-10-10

