Django 接收Post请求数据,并保存到数据库的实现方法

yipeiwu_com5年前Python基础

要说基本操作,大家基本都会,但是有时候,有些操作使用小技巧会节省很多时间。

本篇描述的就是使用dict小技巧,保存到数据库,用来节省大家编码的工作量。

主要内容:通过for循环拿到post表单中的值并保存到一个dict中,然后通过**dict保存到数据库中。

1.用户提交了一个表单,表单内容包含csrf。

2.服务端除了表单中的csrf要过滤掉,其它的都要保存到数据库中。

3.具体看下方代码:

下面的代码分别为修改和保存,其中修改是根据ID修改的。

要注意,

1.保存前的resourcesOld和保存后再获取的resourcesNew是不一样的。

尤其是type【get_type_display()】这个方法,因为要对其进行转义显示,必须获取resourcesNew对象,不然是获取不到转义后的,值只能获取其原值。

2.其次是保存的写法,有的人喜欢用T_Resources.objects.create(id=id,name=name,age=age......),这样每次,

但是都这样写比较繁琐,所以用了下面的写法,两者结果相同,当然还有一种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 = "服务器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 += "标签:" + oldLabel + "->" + newLabel + ','
        writeOperationLog(request, 1, '修改服务器成功,' + 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请求数据,并保存到数据库的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python发送email的3种方法

python发送email还是比较简单的,可以通过登录邮件服务来发送,linux下也可以使用调用sendmail命令来发送,还可以使用本地或者是远程的smtp服务来发送邮件,不管是单个,...

PyCharm鼠标右键不显示Run unittest的解决方法

PyCharm是一个用来写python代码的IDE,很好用。在其中建立了unittest类后,鼠标点击某个test方法后,菜单中会显示Run unittest方法。 问题描述 今天发现一...

Python中利用sqrt()方法进行平方根计算的教程

 sqrt()方法返回x的平方根(x>0)。 语法 以下是sqrt()方法的语法: import math math.sqrt( x ) 注意:此函数是无法直...

Django后端接收嵌套Json数据及解析详解

Django后端接收嵌套Json数据及解析详解

0、干货先写在前 1、前端传值的数据必须使用JSON.stringify()传化 2、后端,通过request.body接收数据,直接使用json.loads解析,解析前,先decod...

如何更优雅地写python代码

前言 Python 这门语言最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。但有时候我们写代码,特别是 Python 初学者,往往还是按照其它语言的思维习惯来写...