使用 Django 和 AJAX 更新数据

Posted

技术标签:

【中文标题】使用 Django 和 AJAX 更新数据【英文标题】:Update data using Django and AJAX 【发布时间】:2021-12-13 02:06:04 【问题描述】:

我在从 Django 数据的输入字段中创建选择字段时遇到问题。 models.py 是:

 class Manifold_monitoring(models.Model):
    MFD_type      = models.ForeignKey(Manifo_types , on_delete=models.CASCADE)
    DATE_TEST     = models.DateField()
    Pressure_MFD  = models.DecimalField(max_digits=15, decimal_places=3,null=True, blank=True)
    Pressure_SP   = models.DecimalField(max_digits=15, decimal_places=3,null=True, blank=True)
    .....
    def __str__(self):
        return str(self.MFD_type.MFDsID.MFDsID +' '+ self.MFD_type.Type +' '+ self.MFD_type.Fluid_N)

    class Meta:
        ordering = ('-post_date',)
        unique_together=[['MFD_type','DATE_TEST']]

以及更新的views.py:

class UpdManifold_Monto(View):
form_class = Manifold_monitoring_F
def get(self,request, pk, *args, **kwargs):
    if request.is_ajax():
        task = Manifold_monitoring.objects.get(pk=pk)
        task.delete()
        return JsonResponse("message":"success")
    return JsonResponse("message": "Wrong request to delete")

def post(self,request, pk, *args, **kwargs):
    if request.is_ajax():
        task = Manifold_monitoring.objects.get(pk=pk)
        print('request.is_ajax()1', task.MFD_type_id)
        data = 
            "MFD_type_id":  task.MFD_type_id,
            "DATE_TEST" :task.DATE_TEST,
            "Pressure_MFD":task.Pressure_MFD,
            "Pressure_SP":task.Pressure_SP
        
        print('request.is_ajax()2', task.MFD_type ,data )
        form = self.form_class(request.POST, initial=data)
        if form.is_valid():
            MFD_type     = form.cleaned_data['MFD_type']
            DATE_TEST    = form.cleaned_data['DATE_TEST']
            Pressure_MFD = form.cleaned_data['Pressure_MFD']
            Pressure_SP  = form.cleaned_data['Pressure_SP']
            print('request.is_ajax()3', MFD_type)
            if form.has_changed():
                task.MFD_type_id  = MFD_type
                task.DATE_TEST    = DATE_TEST   
                task.Pressure_MFD = Pressure_MFD
                task.Pressure_SP  = Pressure_SP 
                task.save()
                return JsonResponse("message": "success")
            return JsonResponse("message":"No change")
        return JsonResponse("message":"Failed")
    return JsonResponse("message": "Wrong request")

编辑表单的html代码:

<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLable" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Edit</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form id="formEdit"  action="">
        % csrf_token %
        <div class="modal-body">
          <div class="form-group validate">
            <input type="text" name="MFD_type" class="form-control" placeholder="Manifold">
            <small class="text-red text-muted mySpan"></small>


          </div>
          <div class="form-group validate">
            <input type="date" name="DATE_TEST" class="form-control" placeholder="Control Date">
            <small class="text-red text-muted mySpan"></small>
          </div>
          <div class="form-group validate">
            <input type="text" name="Pressure_MFD" class="form-control" placeholder="Pressure (bar)">
            <small class="text-red text-muted mySpan"></small>
          </div>
          <div class="form-group validate">
            <input type="text" name="Pressure_SP" class="form-control" placeholder="SP Pressure (bar)">
            <small class="text-red text-muted mySpan"></small>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary btnUpdate">Update</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

因为图像添加和删除工作正常。 所以我将数据库中的这个列表作为下拉列表(选择)。

最后是 AJAX 和 Jquery 脚本:

<script>
//Edit Function
  $("#table_id tbody").on("click",  ".link-edit", function(e)
      e.preventDefault();
      var $this = $(this);
      let MFD_type =     $this.parents(".record").find('td').eq(0).text();
      let DATE_TEST=     $this.data('start');
      let Pressure_MFD = $this.parents(".record").find('td').eq(2).text();
      let Pressure_SP=   $this.parents(".record").find('td').eq(3).text();

      $("#formEdit input[name='MFD_type']").val(MFD_type);
      $("#formEdit input[name='DATE_TEST']").val(DATE_TEST);
      $("#formEdit input[name='Pressure_MFD']").val(Pressure_MFD);
      $("#formEdit input[name='Pressure_SP']").val(Pressure_SP);
      $("#formEdit").attr("action", $this.attr('href'));
      $("#editModal").modal("show");
      return false;
  );

  $("#formEdit").on("submit", function(e)
        e.preventDefault();
        e.stopPropagation();
        var $this = $(this);
        var valid = true;
        $('#formEdit input').each(function() 
            let $this = $(this);
            
            if(!$this.val()) 
                valid = false;
                $this.parents('.validate').find('.mySpan').text('The '+$this.attr('name').replace(/[\_]+/g, ' ')+' field is required');
            
        );
        if(valid)
            let data = $this.serialize();
            $.ajax(
                url: $this.attr("action"),
                type: "POST",
                data: data,
                dataType: "json",
                success: function(resp)
                    if(resp.message === "success")
                        alert("Updated successful");
                        $('#editModal .close').click();
                    
                    else
                        alert(resp.message);
                    
                ,
                error: function(resp)
                    console.log("Something went wrong");
                
            );
        
        return false;
    );
</script>

我想将第一个字段的输入作为选择MFD_type

我是怎么做到的? 我的 ANAX 和 UpdManifold_Monto 函数是否正确?

【问题讨论】:

【参考方案1】:

我准备了动态相关下拉列表的列表。 所以我的观点是

def AddManifold_Monto(request):
 form = Manifold_monitoring_F()
 DrobdownMFD_type = Manifo_types.objects.exclude(Fluid_N = 'Stock')
 model = Manifold_monitoring.objects.filter( DATE_TEST__exact= datetime.date.today())
 context=
  'title':'Manifold Monitoring',
  'model':model,
  'form': form,
  'DrobdownMFD_type':DrobdownMFD_type
  
return render(request,'Home/Production_Ser/MFD_Monitor/ADDMFD_Monitor.html',context)

在 HTML 格式中,我将输入替换为:

    <select id="id_MFD_typeS" name="MFD_typeS" class="select-manifold form-control" required  placeholder="Manifold">
      <option value=""></option>                    
      % for brand in DrobdownMFD_type %
        <option id=" brand.id " value=" brand.id ">
               brand.MFDsID 
        </option>
      % endfor %</select>
    <small class="text-red text-muted mySpan"></small>

所以它可以工作,但是当我更改和更新值时它不会保存

从视图更新功能我刚刚打印了表单值

 form = self.form_class(request.POST, initial=data)
 print(form)

它给了我完整的清单?

> <tr><th><label for="id_MFD_type">Manifold:</label></th><td><ul
> class="errorlist"><li>This field is required.</li></ul><select
> name="MFD_type" required id="id_MFD_type">   <option value=""
> selected>---------</option>
> 
>   <option value="14">AMA CTR HP Prod</option>
> 
>   <option value="15">AMA CTR HP Selectif</option>
> 
>   <option value="16">AMA CTR BP Prod N1</option>
> 
>   <option value="17">AMA CTR BP Prod N2</option>
> 
>   <option value="18">AMA CTR BP Selct N1</option>
> 
>   <option value="19">AMA CTR BP Selct N2</option>
> 
>   <option value="20">AMA MFDS</option>
> 
>   <option value="21">AMA MFDS</option>
> 
> </select></td></tr> <tr><th><label for="id_DATE_TEST">Control
> Date:</label></th><td><input type="date" name="DATE_TEST"
> value="2021-10-28" class="form-control" required id="id_DATE_TEST"
> /></td></tr> <tr><th><label for="id_Pressure_MFD">Pressure
> (bar):</label></th><td><input type="number" name="Pressure_MFD"
> value="33" step="any" id="id_Pressure_MFD" /></td></tr> <tr><th><label
> for="id_Pressure_SP">SP Pressure (bar):</label></th><td><input
> type="number" name="Pressure_SP" value="33" step="any"
> id="id_Pressure_SP" /></td></tr>

【讨论】:

以上是关于使用 Django 和 AJAX 更新数据的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 AJAX 和 Django 从 SQL 数据库更新网站上的字段数据

在 Django 中使用 AJAX 更新数据库

YUI.io (ajax) 和 Django - 更新只能工作一次,YUI 无法再次找到表单

django,ajax:如何有效地实时更新一堆数据

如何使用 Ajax 在 Django 中更新 modelForm

在更新 mysqlDatabase 内容时刷新 django 模板中的表内容