6

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:

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 a name eg.'honda' from my template (as soon as user selects it in drop down) to my view.py which would then fetch the corresponding object and return the result back to my template in 'model' drop down list. (So, basically the car model list refreshes when user selects any car from the car drop down list)

Note: Model is in many-to-many relationship with Car in models.py

I am stuck up here for quite long and any help would be really appreciated.

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

5 Comments

Your summary has been very helpful for me in knowing the basic flow. But I do not exactly want to get the car name. I wanted to fetch data from car 'model' and get the model names displayed on my template. Model and Car are different classes in models.py. I have updated my question above. Thanks @JcKelley !
So for example, a user selects 'Honda' and then another drop down menu now shows 'Accord, Civic, etc' ?
Then you would just query the car.models DB, and send back your data in a dictionary just like the above code.
I have added a link that shows a clear example to your question.
thanks a lot! That link really helped! After a few trials with it, I was able to get what I wanted!
1

I will assume that you are using AJAX requests.

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

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

model_to_dict takes 3 parameters:

  1. A specific model instance
  2. fields to include
  3. fields to exclude

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.