相互依赖的下拉Django JQuery Ajax - 正确的网址

时间:2014-10-24 12:01:19

标签: jquery python ajax django

我已经按照以下教程介绍了如何使用Django和JQuery / Ajax实现相互依赖的下拉列表:http://www.devinterface.com/blog/en/2011/02/how-to-implement-two-dropdowns-dependent-on-each-other-using-django-and-jquery/

我有以下内联表单集,当选择产品类型时,此类型的产品应该是可见的:

enter image description here

选择ProductType时,将调用以下Jquery:

$("select[name$='product_type']").change(function(){

    var url = "/order/" + $(this).val() + "/all_json_models";
    var product_type = $(this).val();
    $.getJSON(url, function(products) {
        var options = '<option value="Z">Select a model</option>';
        for (var i = 0; i < products.length; i++) {
           options += '<option value="' + products[i].pk + '">' + products[i].fields['description'] + '</option>';
        }
        $("select#id_orderline_set-0-product").html(options);
        $("select#id_orderline_set-0-product option:first").attr('selected', 'selected');
        $("select#id_orderline_set-0-product").attr('disabled', false);
    });
})

我在urls.py

中使用了以下内容
(r'^order/(?P<product_type>[-\w]+)/all_json_models/$', 'all_json_models'),

我的order.views.py

def all_json_models(request, product_type):
    current_product_type = ProductType.objects.get(pk=product_type)
    products = Product.objects.all().filter(product_type=current_product_type)
    json_models = serializers.serialize("json", products)
    return HttpResponse(json_models, mimetype="application/javascript")

现在,当我更改产品类型下拉列表时,我收到以下错误:

http://127.0.0.1:8000/order/6/all_json_models/ 500 (INTERNAL SERVER ERROR) 

当我点击链接时:

TypeError at /order/5/all_json_models/
'str' object is not callable

由于这是我第一次使用url引用Ajax,我将失去正确的语法。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

在您的观看次文def all_json_models(request, product_type):中,网址控制器^order/(?P<brand>[-\w]+)/all_json_models/$使用参数brand而不是product_type来调用视图!

要获得更多保护,您可以修改^order/(?P<brand>[-\w]+)/all_json_models/$以仅捕获ID,因为您发送的是product_type ID而不是product_type本身^order/(?P<brand>[-\d]+)/all_json_models/$。你可以做的是发送product_type本身,它有助于SEO;)!

您需要更加小心您的代码,以及处理和捕获异常的方式!

另外:JSON文本的MIME媒体类型是application / json。默认编码为UTF-8。 (来源:RFC 4627)。

答案 1 :(得分:0)

在urls.py中,您使用的是教程语法,但在视图中使用自己的语法。

尝试:

(r'^order/(?P<product_type>[-\w]+)/all_json_models/$', 'all_json_models'),