Django update data with Jquery and AJAX

Hi
I have an issue with this form
I use Jquery AJAX to submit an update.
First, this is my models

class Manifo_types(models.Model):
    MFDsID      = models.ForeignKey(Manifolds, on_delete=models.CASCADE)
    Type        = models.CharField(max_length=10, null=True,blank=True)

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)
    post_date     = models.DateTimeField(auto_now_add=True)
    author         = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    class Meta:
        ordering = ('-post_date',)
        unique_together=[['MFD_type','DATE_TEST']]

and this is the form

class Manifold_monitoring_F(forms.ModelForm):
    MFD_type      = forms.ModelChoiceField(label='Manifold', queryset=Manifo_types.objects.exclude(Fluid_N = 'Stock'))
    DATE_TEST     =  forms.DateField(label='Control Date', widget=forms.DateInput(attrs={"class":"form-control", 'type':'date'}))
    Pressure_MFD  = forms.DecimalField(label='Pressure (bar)',required =False)
    Pressure_SP   = forms.DecimalField(label='SP Pressure (bar)',required =False)
    class Meta:
        model= Manifold_monitoring
        fields=('MFD_type','DATE_TEST','Pressure_MFD','Pressure_SP')

Adding and deleting function works pretty well.

the problem is in the update part and this is the function in 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',data )
            form = self.form_class(request.POST, initial=data)
            print(form)
            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"})

and my Html form is like:

<form id="formEdit"  action="">
        {% csrf_token %}
        <div class="modal-body">
          <div class="form-group validate">

            <select id="MFD_type_idd" name="MFD_type_id" 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 }} {{ brand.Type}} {{ brand.Fluid_N}}
                </option>
              {% endfor %}</select>
            <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>

and the Jqury and AJAX code is :slight_smile:

</script>
//Edit Function

  $("#table_id tbody").on("click",  ".link-edit", function(e){
      e.preventDefault();
      var $this = $(this);
      let MFD_type_id =     $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();
      console.log(MFD_type_id)

      $("#formEdit select[name='MFD_type_id']").val(39); // I fixed the ID don't know how to get it?
      $("#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>

So in the python console, the updating function printed the following (data and form):
the data is correct

{'MFD_type_id': 28, 'DATE_TEST': datetime.date(2021, 10, 28), 'Pressure_MFD': Decimal('55'), 'Pressure_SP': Decimal('55')}

and the form has an issue with MFD_type_id

<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="39">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="4" 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="45" step="any" id="id_Pressure_SP" /></td></tr>

So how I do to solve this?
I think the <select name="MFD_type" required id="id_MFD_type"> should be MFD_type_id`
where I can force this to rename?

and so how I get the $this.parents id to add it.

All my best

The request.POST object is used for accessing HTML form data, not JSON data.

See Request and response objects | Django documentation | Django

You’ll want to either change your AJAX call to submit HTML form data, or change your view to work with request.body.

1 Like

Your use case is perfect for something like HTMX instead of Jquery. You get to use HTML, and only need a couple of extra lines. Check this guide out: Project 1: To Do App