【问题标题】:Django update template QuerySet data with AjaxDjango 使用 Ajax 更新模板 QuerySet 数据
【发布时间】:2020-01-18 05:13:07
【问题描述】:

我必须使用 Ajax 和 Django 视图更新模板上的数据。 在模板中有按钮,shell 根据视图响应更新表上下文。

我已经阅读了几个类似的回复:1、2、3、4、5、6,但找不到解决方案。

模板.html

<button type="submit" class="btn btn-warning vindication" value="vindication">Vindication</button>

<table class="table" align="center">
    <thead class="black">
        <tr>
            <th>Data</th>
        </tr>
    </thead>
    <tbody class="data">
        {% for client in invoices_all_data %}
            <tr>
                <td>{{ client.data }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>

<script>
    $(document).ready(function(){
        $(".vindication").click(function(){

            var vindication_type = $(this).attr("value");
            $.ajax({
                url: "/invoices/vindication_filter/",
                data: {
                    vindication_type : vindication_type,
                },
                type: "POST",
                success: function(response) {
                    $('#data').html(response);
                }
            });
        });
    });
</script>

按钮点击数据发送到views.py函数后处理:

def vindication_filter(request):
    if request.method == 'POST':
        vindication_type = request.POST['vindication_type']

        # filter data
        client_data = MonitoringUsers.objects.all()
        invoices_all_data = MonitoringUsers.objects.none()

        for client in client_data:
            if client.get_all_invoices():
                invoices_all_data = invoices_all_data | MonitoringUsers.objects.filter(
                    user_id=client.user_id, pay_status=vindication_type)


        return TemplateResponse(request, "template.html", locals())

到目前为止,代码正在运行,但我不知道如何将处理后的数据 [invoices_all_data - QuerySet] 返回到主 template.html?

感谢您的任何建议。

【问题讨论】:

    标签: jquery django ajax


    【解决方案1】:

    您不应该返回 TemplateResponse,而是返回带有 HTML 字符串的 JsonResponse,类似于以下内容:

    from django.template.loader import render_to_string
    from django.http import JsonResponse
    
    
    html_rendered = render_to_string('template.html', your_context_dictionary_here)
    return JsonResponse({'html': html_rendered})
    

    然后在 JavaScript 中将 HTML 附加到任何你想要的地方。

    success: function(response) {
        $('#data').html(response['html']);
    }
    

    【讨论】:

    • 上下文是查询集。这种方法会将 invoices_all_data 对象返回到主模板中?
    • 一般来说,当你渲染一个模板时,你会从 Django 视图发送数据。例如,在 HTML 中:

      hello {{name}}

      视图中的上下文可以是 {"name":"Zaraki"}
    • 如果我以 html 形式使用 csrf_token,那么我需要将此令牌传递到视图中,然后将附加数据返回到模板中?
    • @Dalvtor 可以在 ajax 请求后使用 render() 而不是 JsonResponse() 吗?我找不到关于那个主题的任何好的来源,但似乎 JsonResponse() 应该是使用 ajax 的方式。
    【解决方案2】:

    鉴于您的视图是通过ajax 调用的,您只需在视图中通过return invoices_all_data 返回您的invoices_all_data。因此,在您的ajax 中的success 函数中,您使用的response 变量就是您的invoices_all_data。

    def vindication_filter(request):
        if request.method == 'POST':
            vindication_type = request.POST['vindication_type']
    
            # filter data
            client_data = MonitoringUsers.objects.all()
            invoices_all_data = MonitoringUsers.objects.none()
    
            for client in client_data:
                if client.get_all_invoices():
                    invoices_all_data = invoices_all_data | MonitoringUsers.objects.filter(
                        user_id=client.user_id, pay_status=vindication_type)
    
    
            return JsonResponse({'results': list(invoices_all_data )})
    

    模板

    $.ajax({
        url: "/invoices/vindication_filter/",
        data: {
            vindication_type: vindication_type,
        },
        type: "POST",
        success: function(response) {
            //response['results'] is your invoices_all_data
    }
    });
    

    【讨论】:

    • django view 无法返回查询集,响应应该是httpresponse。
    • @Kostas Charitidis 我已经尝试过这个,但现在它不起作用。我将响应中的数据放在 $('#data').html(response); .对吗?
    • @NishantNawarkhede 正确我什至没有看到数据的类型,所以他可以将它们解析为 json 以在 ajax 中处理它们
    • @ZarakiKenpachi 使用 jsonresponse 并使用浏览器中的调试器查看结果。
    • @Kostas Charitidis 我在返回 JsonResponse 时收到错误:'QuerySet' 对象在 site-packages/django/contrib/auth/decorators.py 中没有属性 'user'
    猜你喜欢
    • 2020-08-05
    • 2017-08-14
    • 2021-07-14
    • 2019-02-05
    • 1970-01-01
    • 2017-04-05
    • 2021-12-13
    • 2020-04-18
    • 2021-03-03
    相关资源
    最近更新 更多