16 django 编辑产品


1 后台

  • view
class UpdateProject(View):
    @login_check
    def post(self, request):
        print(request.body)
        body = json.loads(request.body)
        form = ProjectForm(body)
        # print(form)
        if form.is_valid():
            id = body['id']
            proj = Project.objects.filter(id=id)
            print('更新产品:')
            print(proj)
            if proj is not None:
                # 引入model,对数据库进行操作
                Project.objects.filter(id=id).update(proj_name=form.cleaned_data['proj_name'], host = form.cleaned_data['host'])
                result = {'code': 1, 'msg': u'修改产品成功!'}
                return JsonResponse(result,
                                    json_dumps_params={'ensure_ascii': False})
            else:
                result = {'code': -1, 'msg': '产品不存在!'}
                return JsonResponse(result,
                                    json_dumps_params={'ensure_ascii': False})
        else:
            msg = 'message'
            error_dict = json.loads(form.errors.as_json())
            tmp_list = []
            error_list = get_target_value(msg, error_dict, tmp_list)
            # print(error_list)
            result = {'code': -1, 'msg': error_list[0]}
            return JsonResponse(result,
                                json_dumps_params={'ensure_ascii': False})
  • urls
urlpatterns = [
    path('update', UpdateProject.as_view(), name='update'),

]

2 前台

  • 编辑js
// 更新产品
export const project_update = (form) => {
    return fetch(baseurl + '/v1/project/update', {
        method: 'POST',
        body: JSON.stringify(form),
        headers: new Headers({'Content-Type': 'application/json',
            'authorization': localStorage.getItem('token')}),
    }).then(response => {
        return response.json()
    })
}
  • 点击列表后的编辑链接
        // 编辑操作
        handleEdit(index, row) {
          this.idx = index;
          this.form = row;
          this.form.id = row.id
          this.editVisible = true;
        },
  • 编辑后点确定
// 保存并确定
        saveEdit() {
          this.$refs.form.validate(valid => {
            if (valid) {
              project_update(this.form).then(res => {
                if (res.code === 1){
                  console.log(res)
                  this.editVisible = false;
                  this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                  this.form.proj_name = ''
                  this.form.host = ''
                  this.getData()
                }else {
                  this.$message.success(`修改第 ${this.idx + 1} 行失败`);
                  this.editVisible = false;

                }
              })

            } else {
              this.$message.error("产品信息输入错误");
              return false;
            }
          });
        }

相关