【问题标题】:Context from Django Render Not Displaying Till Refresh?来自 Django 渲染的上下文在刷新前不显示?
【发布时间】:2018-03-15 08:49:42
【问题描述】:

我正在使用 AJAX 调用向我的视图发布一个值。 从我的观点来看,我正在根据传递给我的视图的值(id)找到产品。我将它添加到我的发票中并将其应用到我在视图底部呈现的上下文中。在我刷新之前不会显示上下文,但我不能这样做。我被卡住了。

...
elif request.is_ajax():
    product_id = request.POST.get('value')
    if product_id:
        product_info = Product.objects.get(id=product_id)
        new_invoice_product = InvoiceProduct.objects.create(invoice_product_set=product_info)
        invoice.attached_products.add(new_invoice_product)
        context['attached_products'] = invoice.attached_products.all()
...

return render(request, 'inventory/invoice_create.html', context)

【问题讨论】:

    标签: ajax django django-templates django-views


    【解决方案1】:

    您不能直接通过服务器重新渲染客户端的 HTML DOM。

    通过 DjangoTemplate 引擎,它只是渲染然后响应 HTML 本身。这意味着您无法使用 ajax 更新客户端的 DOM,除非您更新根元素 <html>。 (这将与重新加载页面相同!)

    所以你可能想用一些数据更新 DOM 树,用 ajax 调用然后只用jsonfile 更新。如果你使用JsonResponse,那么你可以通过AJAX响应对象来获取它。

    那么你要做的不是django模板而是JavaScript编程。

    在你的views.py中,这样做:

    # in your views.py
    ...
    elif request.is_ajax():
        product_id = request.POST.get('value')
        if product_id:
        product_info = Product.objects.get(id=product_id)
        new_invoice_product = InvoiceProduct.objects.create(invoice_product_set=product_info)
        invoice.attached_products.add(new_invoice_product)
        context['attached_products'] = invoice.attached_products.all()
        # return render(request, 'inventory/invoice_create.html', context) # NOT render but do like this:
        return JsonResponse({
            'new_data': {
                'id': new_invoice_product.id
                # and other informations you want...
            }
        })
    

    在你的 HTML 中,这样做:

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous"></script>
    <script>
        // in your HTML
        // guessing you're using jquery..
        $.ajax({
            url: "test.html",
            context: document.body
        }).done(function (json) {
            $('yourSelector').append(json['new_data']['id']);
        });
    </script>
    

    请记住,这段代码只是 sn-p 不是完全工作的代码。如果您想了解更多示例,请查看链接:

    https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html

    【讨论】:

    • 嗯,我不明白的问题是我在我的模板中循环,它应该显示“attached_products”,这是我的发票模型中的一个多对多字段,它将产品附加到某些发票。还会这样吗?
    • 所以概念很简单,“你不能在客户端重写 HTML”。 django 模板引擎仅适用于服务器端渲染。如果您使用 AJAX,则它不起作用。所以你必须用JS做客户端渲染。它与 MTM 模型无关,因为呈现的 HTML 只是“字符串”而不是真正的 python 模型。
    • 好吧,这是有道理的。你认为我的问题需要跟上吗?
    • 工作就像一个魅力!现在只好重新组织事情了!谢谢!
    • @OhGreatOne 很高兴听到这个消息:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 2012-05-12
    • 1970-01-01
    • 2011-01-10
    • 2019-01-14
    • 2019-01-05
    • 2021-11-22
    相关资源
    最近更新 更多