ajax - Django:使用 Ajax 获取模板中的数据库对象值

标签 ajax django jquery

我想根据用户选择获取数据库对象。我知道 Ajax 是一种可能的解决方案,但我不知道如何实现。这是代码:

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>

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

注意:models.py中的Model与Car是多对多关系

我在这里被困了很长时间,如果有任何帮助,我将不胜感激。

最佳答案

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

模板.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>");                
            }
        });
    });
});

View .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“发布”给自身,意识到这是一个 AJAX 调用并调用 AJAX 函数
  • Django 看到操作是“add_car”并执行 if 语句
  • Django 使用您发送的 ID 查询数据库,返回一辆汽车
  • Django 将该数据作为 JSON 对象(在本例中为字典)发送回页面
  • JQuery 使用传递的信息更新页面。

如果您想查看清晰的示例,请参阅此 Link

关于ajax - Django:使用 Ajax 获取模板中的数据库对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17192916/

相关文章:

javascript - 模态接收错误数据

php - 如何使 Codeigniter 中的分页类与 AJAX 一起工作?

javascript - 弹出表单数据不插入数据库

javascript - 如何使 php 操作保留在此页面上,直到我使用 JQuery 退出?

python - 在终端中运行 django python 文件

python - 没有名为 rest_auth 的模块

jquery - 如何使工具提示(qtip2)位于顶部中心?以及如何在其中添加图像?

javascript - 如何使用ajax上传文件?

python - 在使用管理面板插入模型字段之前对其进行预处理

javascript - 未调用插件函数中的 setInterval()