Django update data with Jquery and AJAX

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',)

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

Adding and deleting function works pretty well.

the problem is in the update part and this is the function in

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)
            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,
            print('request.is_ajax()2',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 
                    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="{{ }}" value="{{ }}">
                      {{ brand.MFDsID }} {{ brand.Type}} {{ brand.Fluid_N}}
              {% endfor %}</select>
            <small class="text-red text-muted mySpan"></small>

          <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 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 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 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>

and the Jqury and AJAX code is :slight_smile:

//Edit Function

  $("#table_id tbody").on("click",  ".link-edit", function(e){
      var $this = $(this);
      let MFD_type_id =     $this.parents(".record").find('td').eq(0).text();
      let DATE_TEST=     $'start');
      let Pressure_MFD = $this.parents(".record").find('td').eq(2).text();
      let Pressure_SP=   $this.parents(".record").find('td').eq(3).text();

      $("#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'));
      return false;

  $("#formEdit").on("submit", function(e){
        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');
            let data = $this.serialize();
                url: $this.attr("action"),
                type: "POST",
                data: data,
                dataType: "json",
                success: function(resp){
                    if(resp.message === "success"){
                        alert("Updated successful");
                        $('#editModal .close').click();
                error: function(resp){
                    console.log("Something went wrong");
        return false;

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

{'MFD_type_id': 28, 'DATE_TEST':, 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>

<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