Sunday, February 23, 2020

How to use the ajax response data to fill Multiple ManyToManyFields in django

    1.I am a Django learner.      2.I don't have much knowledge on jquery & Ajax.      3.I have two models ModelRegister and ModelGSPRequest in Models.py.       4.I have a requirement to populate 2 ManyToManyFields in ModelGSPRequest with the data based on selected drop down value,which is a Foreign Key to ModelRegister.      5.To accomplish this requirement ,i have written an Ajax function named load_model_details which triggers when there is a change in the model name drop down selection.         Through this method i.e.,load_model_details i got all the model instances for the selected model & then i am passing it as a context to model_info_options.html         to get the model number and OS Name details for the selected model.      6.Lets consider i have Model Register Model with below Table Data.      7.If user selectedmodel name:G5 modelNumber filled with H850,H860,O and P.[ its populatedwith both model number and os name data ]        But it should contain only H850,H860 .         Similarly os name filled with H850,H860,O and P but it should be only O and P.       8.So , Please suggest the proper way of accessing the response data in success method to display the correct data as per expected.
ModelRegister   
ModelNameModelNoOSNamechipset
G1G100Oqct
G2G110Oqct
G5H850Oqct
G5H860Oqct
G5H850Pqct
G5H860Pqct
Below is my code.
Models.py:  ---------      class ModelRegister(models.Model):          'This class is used to register the model'.                        model_name = models.CharField(max_length=128, verbose_name="ModelName")          model_no = models.CharField(max_length=128, verbose_name="ModelNo")          os_name = models.ForeignKey(OSName, on_delete=models.CASCADE, verbose_name="OSName",default=" ")             class Meta:              verbose_name_plural = "ModelRegisteredList"            def __str__(self):              return self.model_name          class ModelGSPRequest(models.Model):      'This class is used to raise Model GSP request for a selected model using   registered_model.'            registered_model = models.ForeignKey(ModelRegister,on_delete=models.CASCADE,       verbose_name="ModelName")            registered_model_no = models.ManyToManyField(ModelNumber,default="")          registered_model_os_name = models.ManyToManyField(OSNames,default="")          model_gsp_requester = models.CharField("Model GSP Requester", max_length=128,default=" ")               def __str__(self):              return self.model_gsp_requester+str(self.pk)

id_form-0-registered_model_no -> This is the id of the registered_model_no in my html ModelGSPRequest form.      id_form-0-registered_model_os_name -> This is the id of the registered_model_os_name in my html ModelGSPRequest form.        Model Register is a table with below data:      -----------------------------------------      [![Model Register Table Data][1]][1]         Consider Model Register table data  as given below:      ****Model Name              Model No               OSName****         ---------------------------------------------------------            G5                    H850                     O            G5                    H860                     O            G5                    H850                     P            G5                    H860                     P            G7                    G710                     P            G7                    G712                     P                 1.ModelGSPRequest Model has a registered_model field, which is foreign key to ModelRegister to         choose the modelname.      2.For example, when user selects model G5.        I want to AutoFill registered_model_no  with the values: H850 and H860         [registered_model_no: ManyToManyField ] and registered_model_os_name with the values of O and P         [ registered_model_os_name:ManyToManyField ]            With below code , when i select model name , both modelnumber and OSName details are updated .      But registered_model_no should have only model number details and registered_model_os_name should have only OS Name details as shown in screen shot below.        [![enter image description here][2]][2]        Please suggest how to access model_info_options.html data in success method during ajax call. 

Ajax.py:

=======

Below is the code snippet used get the model instances for the selected model

    def load_model_details(request):          print("load model details")          print("request method",request.method)            modelname = request.GET.get("model")`enter code here`          model_registered_instances = ModelRegister.objects.filter(model_name=modelname)          return render(request, 'model_info_options.html', {'model_registered_instances':model_registered_instances})

gspapp/templates/gspapp/model_info_options.html:

    <!DOCTYPE html>      <html lang="en">          {% for model in model_registered_instances %}      <option value="{{ model.pk }}">{{ model.model_no }}</option>          {% endfor %}            {% for model in model_registered_instances %}      <option value="{{ model.pk }}">{{ model.os_name }}</option>          {% endfor %}      </html>

ModelGSPRequest.html:

    `This is the html which is used to select the model name to auto fill the Registered Model Number and OS Name details based on selected model`        `Below is the code snippet for Ajax call inside java script. `        <script type="text/javascript">              $("#id_form-0-registered_model").change(function () {                var modelname = $(this).val();  // get the selected model from the HTML input                $.ajax({                          // initialize an AJAX request                  url: "load_model_details",                       data: {                      'model': modelname       // add the modelname to the GET parameters                  },                  success: function (data) {   // `data` is the return of the `load_model_details` view function [ i.e.,the data returned from model_info_options.html]                        $("#id_form-0-registered_model_no").html(data);  // replace the contents of the city input with the data that came from the server                      $("#id_form-0-registered_model_os_name").html(data);                  }                  });              });      </script>
Please suggest how to access model_info_options.html with the proper data in success method during ajax call & fill the registered model no and os name fields correctly for the selected model.. 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/312d23b9-8bc3-49c1-86e0-e9681c6a1f96%40googlegroups.com.

No comments:

Post a Comment