Django 接收Post請求數(shù)據(jù),并保存到數(shù)據(jù)庫的實現(xiàn)方法
要說基本操作,大家基本都會,但是有時候,有些操作使用小技巧會節(jié)省很多時間。
本篇描述的就是使用dict小技巧,保存到數(shù)據(jù)庫,用來節(jié)省大家編碼的工作量。
主要內(nèi)容:通過for循環(huán)拿到post表單中的值并保存到一個dict中,然后通過**dict保存到數(shù)據(jù)庫中。
1.用戶提交了一個表單,表單內(nèi)容包含csrf。
2.服務(wù)端除了表單中的csrf要過濾掉,其它的都要保存到數(shù)據(jù)庫中。
3.具體看下方代碼:
下面的代碼分別為修改和保存,其中修改是根據(jù)ID修改的。
要注意,
1.保存前的resourcesOld和保存后再獲取的resourcesNew是不一樣的。
尤其是type【get_type_display()】這個方法,因為要對其進(jìn)行轉(zhuǎn)義顯示,必須獲取resourcesNew對象,不然是獲取不到轉(zhuǎn)義后的,值只能獲取其原值。
2.其次是保存的寫法,有的人喜歡用T_Resources.objects.create(id=id,name=name,age=age......),這樣每次,
但是都這樣寫比較繁瑣,所以用了下面的寫法,兩者結(jié)果相同,當(dāng)然還有一種save的寫法,這里就不再闡述了!
def resources(request):
if request.method == 'GET':
return render(request, 'docker/Resources.html', )
else:
systemDict = {}
for key in request.POST:
if key != 'csrfmiddlewaretoken':
systemDict[key] = request_postData.get(key)
if 'id' in request_postData:
result = {'code': 401, 'message': '修改失??!', 'data': None}
try:
resourcesOld=T_Resources.objects.get(id=systemDict['id'])
T_Resources.objects.filter(id=systemDict['id']).update(**systemDict)
resourcesNew=T_Resources.objects.get(id=systemDict['id'])
result['code'] = 201
result['message'] = '修改成功'
logInfo = "服務(wù)器IP:" + resourcesOld.ip + ","
if resourcesOld.name != resourcesNew.name:
logInfo += "名稱:" + resourcesOld.name + "->" + resourcesNew.name + ','
if resourcesOld.type != resourcesNew.type:
logInfo += "類型:" + resourcesOld.get_type_display() + "->" + resourcesNew.get_type_display() + ','
if resourcesOld.label != resourcesNew.label:
oldLabel = list(T_Label.objects.filter(type='T_Resources', value__in=resourcesOld.label).values_list('name', flat=True))[0]
newLabel = list(T_Label.objects.filter(type='T_Resources', value__in=resourcesNew.label).values_list('name', flat=True))[0]
logInfo += "標(biāo)簽:" + oldLabel + "->" + newLabel + ','
writeOperationLog(request, 1, '修改服務(wù)器成功,' + logInfo)
except:
pass
return HttpResponse(json.dumps(result, ensure_ascii=False))
else:
result = {'code': 401, 'message': '添加失??!', 'data': None}
try:
id=T_Resources.objects.create(**systemDict).id
resources=T_Resources.objects.get(id=id)
result['code'] = 201
result['message'] = '添加成功'
except:
pass
return HttpResponse(json.dumps(result, ensure_ascii=False))
以上這篇Django 接收Post請求數(shù)據(jù),并保存到數(shù)據(jù)庫的實現(xiàn)方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用CodeMirror實現(xiàn)Python3在線編輯器的示例代碼
這篇文章主要介紹了使用CodeMirror實現(xiàn)Python3在線編輯器的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01
python使用BeautifulSoup分頁網(wǎng)頁中超鏈接的方法
這篇文章主要介紹了python使用BeautifulSoup分頁網(wǎng)頁中超鏈接的方法,涉及Python使用BeautifulSoup模塊操作網(wǎng)頁鏈接的技巧,需要的朋友可以參考下2015-04-04

