Django:使用Ajax在模板中获取数据库对象值 [英] Django: Get database object value in template using Ajax

查看:259
本文介绍了Django:使用Ajax在模板中获取数据库对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据用户选择提取数据库对象。我知道一个可能的解决方案可能是Ajax,但我不知道如何得到它。以下是代码:

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>

这里,我想从我的模板传递一个名字eg.'honda'(只要用户在我的view.py中选择它,然后它将提取相应的对象,并将结果返回到模型下拉列表中的模板。 (因此,当用户从汽车下拉列表中选择任何一辆车时,基本上汽车型号列表将刷新)

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)

注意:我在Cars.py中与Car的很多关系

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.

推荐答案

您可以使用AJAX回调Django代码并返回您的车名:

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

template.html

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')


  • 通过Ajax发送汽车的id回到Django。

  • Django'post'到自己,实现它是一个AJAX调用并调用AJAX函数

  • Django看到的动作是'add_car'并执行if语句

  • Django使用您发送的ID查询数据库,返回汽车

  • Django将该数据作为JSON对象发送回该页面(在这种情况下为字典) )

  • JQuery使用传递的信息更新页面。

  • 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

这篇关于Django:使用Ajax在模板中获取数据库对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆