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",
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
source share