Django: Get database object value in template using Ajax

后端 未结 2 1767
耶瑟儿~
耶瑟儿~ 2021-02-02 04:26

I want to fetch database object depending on user selection. I know one possible solution could be Ajax, but I don\'t know how to get about it. Here is the code:

2条回答
  •  忘了有多久
    2021-02-02 04:51

    You can use AJAX to call back to your 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(""+data.car+"");                
                }
            });
        });
    });
    

    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 in summary, here is what you're doing:

    • Sending the 'id' of the car back to Django through Ajax.
    • Django 'posts' to itself, realizes it is an AJAX call and calls the AJAX function
    • Django see's that the action is 'add_car' and executes if statement
    • Django queries the DB using the id you sent it, returning a car
    • Django sends that data back to the page as a JSON object (a dictionary in this case)
    • JQuery updates the page using the passed information.

    If you want to see a clear cut example, please see this Link

提交回复
热议问题