【问题标题】:Django render loading page then load actual pageDjango 渲染加载页面然后加载实际页面
【发布时间】:2019-03-13 14:58:10
【问题描述】:

我要加载的实际页面需要相当多的时间,因为它查询 API 以获取大量数据(python 正在执行后端查询)。如何渲染我的加载页面,然后在收集数据后渲染我的实际页面。

我在 view.py 中想要做什么

class Page(ListView):

       def loading(request):
            return render(request,'loading.html')

       def viewProfile(request, player_name):
            Page.loading(request)

            context = {
                'data1' : query_api(1),
                'data2' : query_api(2),
                'data3' : query_api(3),

            } 
            return render(request, 'actualpage.html', context)

【问题讨论】:

    标签: python django python-3.x django-templates


    【解决方案1】:

    在您的加载页面中,向将查询 api 的视图发出 ajax 请求,并在成功回调中设置模板中的 html 数据。

    但是,如果 api 需要很多时间,我建议您使用 celery 进行异步处理,以便您的用户可以正常浏览网站而不是等待。

    在您的模板中 -

    $.ajax({
                url: "<query_view_url>",
                type: "GET",
                dataType: 'json',
                success: function (data){
                    $("#div_id").html(data.query_data);
                },
                error: function(e){
                    console.log(e);
                }
            });
    

    在你的views.py-

    def view_of_query_url(request, <other parameters>):
        <query_logic>
        data = dict()
        data['query_data'] = <your_queried_data>  # In html format using render_to_string
        return JsonResponse(data)
    

    【讨论】:

    • 难道不是js是查询而不是python?
    • @AjayShah 不,你发送一个ajax请求来查询API,这将在views.py中处理。从 JsonResponse 中返回视图的结果,该结果将在成功回调中接收。然后将结果设置为 html 元素,如 div
    • 你能给我看一个例子来说明这个方法是什么样的吗?
    • @AjayShah 看看我更新的答案。使用render_to_string 设置&lt;your_queried_data&gt; 使其像html。你可以谷歌一下
    猜你喜欢
    • 1970-01-01
    • 2014-09-08
    • 2020-10-04
    • 2016-07-12
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    相关资源
    最近更新 更多