Django: get the value of a database object in a template using Ajax

I want to get the database object depending on the user's choice. I know that one of the possible solutions could be Ajax, but I donโ€™t know how to do it. Here is the code:

view.py:

def automation(request): //some code car = CAR.objects.get(ida_name='honda') model = car.model_set.all() //some code 

template.html:

 Select CAR: <select id="car" name="car"> {% for car in car_list %} <option value="{{ car.id }}" id="{{ car.id }}">{{ car.car_name }}</option> {% endfor %} </select> Select car model: <select id="model" name="model"> {% for model in car.model_set.all %} <option value="{{ forloop.counter }}">{{ model.model_name }}</option> {% endfor %} </select> 

Here I want to pass the name eg.'honda 'from my template (as soon as the user selects it from the drop-down list) to my view.py, which will then select the appropriate object and return the result back to my template in the "model" drop-down list. (So โ€‹โ€‹basically the list of car models is refreshing when the user selects any car from the drop-down list of cars)

Note. A model is in many ways to many with Car in models.py

I have been stuck here for quite some time and any help would really be appreciated.

+4
source share
2 answers

You can use AJAX to call the Django code and return the name of your car:

template.html

 $(document).ready(function () { $(document).on("click",'.car_add', function() { $car_id = $(this).attr('id') $.ajax({ type: "POST", // This is the dictionary you are SENDING to your Django code. // We are sending the 'action':add_car and the 'id: $car_id // which is a variable that contains what car the user selected data: { action: "add_car", id: $car_id }, success: function(data){ // This will execute when where Django code returns a dictionary // called 'data' back to us. $("#car").html("<strong>"+data.car+"</strong>"); } }); }); }); 

views.py

 def post(self,request, *args, **kwargs): if self.request.is_ajax(): return self.ajax(request) def ajax(self, request): response_dict= { 'success': True, } action = request.POST.get('action','') if action == 'add_car': car_id = request.POST.get('id','') if hasattr(self, action): response_dict = getattr(self, action)(request) car = CAR.objects.get(ida_name='car_id') response_dict = { 'car_name':car.name } return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json') 

So here is what you do:

  • Sending the "id" of the car back to Django via Ajax.
  • Django "sends" to itself, realizes that it is an AJAX call and calls the AJAX function
  • Django sees the action is "add_car" and executes if statement
  • Django queries the database using the identifier you sent, returning the car
  • Django sends this data back to the page as a JSON object (in this case, a dictionary)
  • JQuery refreshes the page using the transmitted information.

If you want to see a simple example, see link Link

+3
source

I assume you are using AJAX requests.

You cannot directly return the result of a query or an instance of a model as JSON. But you can serialize it. Here is one of the possibilities:

 from django.forms.models import model_to_dict model_to_dict(intance, fields=[], exclude=[]) 

model_to_dict takes 3 parameters:

  • Specific model instance
  • to enable
  • fields to exclude

Parameters 2 and 3 are optional. If you do not specify fields, the method will serialize all of them. To do this for multiple instances (for example, the result of a query), simply do this in a loop for each instance.

0
source

Source: https://habr.com/ru/post/1487051/


All Articles