django -在Django数据加载时加载模板并添加一个加载微调器

fkvaft9z  于 2023-04-22  发布在  Go
关注(0)|答案(1)|浏览(118)

当我打开我的Django项目时,我想首先加载body.html,然后加载dashboard.html。dashboard.html是一个很重的文件,因为它在script标签中使用python数据框。所以首先我想显示body.html,一旦body.html被渲染,在dashboard.html及其python Django数据加载时添加一个加载微调器
这段代码没有显示Highcharts数据,因为body类(DashboardGraphs)不包含Django数据,所以body.html中没有显示数据
所以,问题是我如何首先加载body.html,然后加载dashboard.html,dashboard.html位于body.html(dashboard-container)中。使用我展示的代码,这正在发生,但图表没有显示数据。
这是body.html现在x1c 0d1x
这是dashboard.html

谢谢。

urls.py

path('dashboard_graphs', DashboardViewFinal.as_view() , name='dashboard_graphs'),
path('dashboard', DashboardGraphs.as_view() , name='dashboard'),

views.py

class DashboardViewFinal(LoginRequiredMixin, TemplateView):

    def __init__(self):
        self.dashboard_view_23 = DashboardView(2023,'2023')
        self.year_int_2023 = 2023
        self.year_str_2023 = str(2023)

        self.dashboard_view_22 = DashboardView(2022, '2022')
        self.year_int_2022 = 2022
        self.year_str_2022 = str(2022)

    template_name = 'dashboard.html'

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    # -----------------------------------------------
    # Conexion con HTML
    # -----------------------------------------------

    def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)
        context['panel'] = 'Panel de administrador'       

        
        context['month_total_2022'] = self.dashboard_view_22.get_graph_month_total()
        context['alumnos_mens_total_valor_2022'] = self.dashboard_view_22.get_graph_alumnos_mensual()
        context['month_total_2022'] = self.dashboard_view_22.get_graph_month_total()
        context['ingresos_total_2022'] = self.dashboard_view_22.get_ingresos_total()[0]
        context['egresos_total_2022'] = self.dashboard_view_22.get_ingresos_total()[1]
        context['saldo_total_2022'] = self.dashboard_view_22.get_ingresos_total()[2]

        context['month_total_2023'] = self.dashboard_view_23.get_graph_month_total()
        context['alumnos_mens_total_valor_2023'] = self.dashboard_view_23.get_graph_alumnos_mensual()
        context['month_total_2023'] = self.dashboard_view_23.get_graph_month_total()
        context['ingresos_total_2023'] = self.dashboard_view_23.get_ingresos_total()[0]
        context['egresos_total_2023'] = self.dashboard_view_23.get_ingresos_total()[1]
        context['saldo_total_2023'] = self.dashboard_view_23.get_ingresos_total()[2]      

        return context

class DashboardGraphs(LoginRequiredMixin, TemplateView):
    template_name = 'hzt/body.html'

body.html

{% extends 'home.html' %}
{% block body %}
    <body class="hold-transition sidebar-mini" >
        
    <div class="wrapper">

        <!-- Header -->
        {% include 'hzt/header.html' %}
        <!-- Content -->
        {% include 'hzt/navbar.html' %}

        <div class="content-wrapper">
            <div class="content">                    
                    {% block content %}
                    <div id="dashboard-container"></div>
                    <div id="spinner" class="loading-icon" style="display: none;">
                        <img style="height:50%; width: 100%;" src="https://media.tenor.com/6gHLhmwO87sAAAAi/gg.gif" alt="Loading..."/>
                    </div>
                    {% endblock %}
            </div>
        </div>
        
        
    </div> 
    <!-- Block javascript -->
    {% block javascript %}


    <script>

        function loadDashboard() {
            const container = document.getElementById('dashboard-container');
            const spinner = document.getElementById('spinner');
            //const dashboard = initDashboardGraphs();
            spinner.style.display = 'block';

            
            fetch('{% url "erp:dashboard_graphs" %}')
                .then(response => response.text())
                .then(html => {
                    container.innerHTML = html;
                    const dashboard = window.initDashboardGraphs();
                    dashboard.showYear(2023);                    
                    spinner.style.display = 'none';
                })
                .catch(error => {
                    console.error('Error loading dashboard:', error);
                    spinner.style.display = 'none';
                });
                 
        }

        

        document.addEventListener('DOMContentLoaded', function () {
            loadDashboard();
            
            
        });

    </script>
{% endblock %}
    </body>
{% endblock %}

dashboard.html

{% block content %}

    <div class="container">
        <!-- Mes y año -->
        <div class="info-box mb-3 bg-warning">
            <span class="info-box-icon"><i class="fa fa-calendar"></i></span>
            <div class="info-box-content padding-top">
                <h1><span class="info-box-text">2023</span>
                    <span class="info-box-number">HOLA</span>
                </h1>
            </div>
            <!-- /.info-box-content -->
        </div> 
    </div>   

    

    <div class="container-fluid">
        
        <div class="row">
            <!-- Ingresos y egresos - mensual -->
            <div class="col-md-6">
                <div class="card bg-gradient-primary">
                    <div class="card-body">

                        <div id="container" style="height: 100%; width: 100%; min-height: 250px"></div>
                    </div>
                    <!-- /.card-body-->
                </div>
            </div>
            <!-- Alumnos Total - mensual -->
            <div class="col-md-6">
                <div class="card bg-gradient-primary">
                    <div class="card-body">
                        <div id="container-72" style="height: 250px; width: 100%;"></div>
                    </div>
                    <!-- /.card-body-->
                </div>
            </div>
        </div>
        <div class = "padre" >
            <ul class="nav justify-content-center">
                <nav>
                    <div class="nav nav-tabs" id="nav-tab" role="tablist">
                        <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true">Ingresos y Egresos</a>

                    </div>
                </nav>
            </ul>
        </div>

        <div class="tab-content" id="nav-tabContent">

            <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">             
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">Ingresos y Gastos, proporción del total</h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-plus"></i></button>
                            <button type="button" class="btn btn-tool" data-card-widget="remove"><i class="fas fa-times"></i></button>
                        </div>
                    </div>
                    <div class="card-body" style="display: none;">
                        <div class="row">
                            <div class="col-lg-6">
                                <div id="container-11" style="min-height: 250px; height: 450px; max-height: 550px; max-width: 100%;"></div>
                            </div>
                            <div class="col-lg-6">
                                <div id="container-12" style="min-height: 250px; height: 450px; max-height: 550px; max-width: 100%;"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">Gastos Variables</h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-plus"></i></button>
                            <button type="button" class="btn btn-tool" data-card-widget="remove"><i class="fas fa-times"></i></button>
                        </div>
                    </div>
                    <div class="card-body" style="display: none;">
                        <div class="chart" >
                            <div id="container-130" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


<script type="application/javascript">
    function initDashboardGraphs() {

    const month_total_2022 =                      {{month_total_2022|safe}}
    const month_total_2023 =                      {{month_total_2023|safe}}
    const graph_ingresos_total_2022 =             {{graph_ingresos_total_2022|safe}}
    const graph_egresos_total_2022 =             {{graph_egresos_total_2022|safe}}
    const graph_saldo_total_2022 =                 {{graph_saldo_total_2022|safe}}
    const graph_ingresos_total_2023 =             {{graph_ingresos_total_2023|safe}}
    const graph_egresos_total_2023 =             {{graph_egresos_total_2023|safe}}
    const graph_saldo_total_2023 =                 {{graph_saldo_total_2023|safe}}
    const alumnos_mens_total_valor_2022 =         {{alumnos_mens_total_valor_2022|safe}}
    const alumnos_mens_total_valor_2023 =         {{alumnos_mens_total_valor_2023|safe}}


    function createHighchartsColumn(containerId, chartTitle, chartSubtitle, xAxisCategories, yAxisTitle, yAxisMin, plotOptions, tooltipFormatter, seriesData) {
             return Highcharts.chart(containerId, {
                 chart: {
                     type: 'column',
                     borderColor: '#000000',
                     borderWidth: 1,
                 },
                 title: {
                     text: chartTitle
                 },
                 subtitle: {
                     text: chartSubtitle
                 },
                 xAxis: {
                     categories: xAxisCategories,
                     crosshair: true
                 },
                 yAxis: {
                     min: yAxisMin,
                     title: {
                         text: yAxisTitle
                     }
                 },
                 tooltip: {
                     headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                     pointFormat: tooltipFormatter,
                     footerFormat: '</table>',
                     shared: true,
                     useHTML: true
                 },
                 plotOptions: plotOptions,
                 series: seriesData
             });
         }

    var IngyEgrTotal = Highcharts.chart('container', {
                                 chart: {
                            type: 'column'
                        },
                        title: {
                            text: 'Ingresos y Egresos'
                        },
                        subtitle: {
                            text: 'mensual'
                        },
                        xAxis: {
                            categories: {{month_total_2023|safe}},
                            crosshair: true
                        },
                        yAxis: {
                            min: -10000,
                            title: {
                                text: '$'
                            }
                        },
                        tooltip: {
                            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                                '<td style="padding:0"><b>{point.y:.1f} $</b></td></tr>',
                            footerFormat: '</table>',
                            shared: true,
                            useHTML: true
                        },
                        plotOptions: {
                            column: {
                                pointPadding: 0.2,
                                borderWidth: 0
                            },
                            series: { borderColor: '#303030'},
                        },
                        series: [{
                                                name: 'Ingresos',
                                                color: 'green',
                                                
                                                data: {{graph_ingresos_total_2023 | safe}}

                                            }, {
                                                name: 'Egresos',
                                                color: 'orange',
                                                
                                                data: {{graph_egresos_total_2023 | safe}}

                                            }, {
                                                name: 'Saldo',
                                                'negativeColor': 'red',
                                                
                                                data: {{graph_saldo_total_2023 | safe}}

                                            } 
                                                 ]

                                             });

    var AlumnosTotMes = createHighchartsColumn(
             'container-72',
             'Alumnos totales, por mes',
             '',
             {{ month_total_2023 | safe }},
             'Cantidad',
             0,
             { series: { borderColor: '#303030' } },
             '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                 '<td style="padding:0"><b>{point.y:.1f}</b></td></tr>',
             [{ name: 'Cantidad', showInLegend: false, data: {{ alumnos_mens_total_valor_2023 | safe }} }]
         );                                         

    var chartObjects = [
                {
                    chart: IngyEgrTotal,
                    data: () => {
                        var ingresos = (year === 2022) ? graph_ingresos_total_2022 : graph_ingresos_total_2023;
                        var egresos = (year === 2022) ? graph_egresos_total_2022 : graph_egresos_total_2023;
                        var saldo = (year === 2022) ? graph_saldo_total_2022 : graph_saldo_total_2023;
                        return [
                            { data: ingresos },
                            { data: egresos },
                            { data: saldo }
                        ];
                    }
                },
                
                { chart: AlumnosTotMes, data: () => (year === 2022) ? {{ alumnos_mens_total_valor_2022 | safe }}  : {{ alumnos_mens_total_valor_2023 | safe }}  }, 
            ];     

    var year = 2023; // Default year

    function showYear(selectedYear) {
      year = selectedYear;
      var month_total = (year === 2022) ? month_total_2022 : month_total_2023;

      chartObjects.forEach(chartObject => {
          chartObject.chart.update({
              xAxis: {
                  categories: month_total
              },
              series: chartObject.data()
          });
      });

      const spinner = document.getElementById('spinner');
        spinner.style.display = 'none';

      

    }
}
</script>
iezvtpos

iezvtpos1#

未显示的图表:

dashboard.html内部的<div class="container-fluid" style="display:none;">永远不会关闭,因此您永远不会显示Div!
但是改变这个参数并不会给予你想要的结果。这意味着当微调器已经显示,提取完成,你等待了-排序击败的目的!

期望行为:

将Spinner移到body.html中,再做一些小的修改,* 应该 * 会给予你想要的结果。

1移动微调器

删除dashboard.html中的微调器元素,并将其放置在body.html中,如下所示:

<div class="content-wrapper">
  <div class="content">                    
  {% block content %}
    <div id="dashboard-container">

      <!-- Show spinner on load -->
      <div id="spinner" class="loading-icon">
          <img style = "height:50%; width: 100%;" src="https://media.tenor.com/6gHLhmwO87sAAAAi/gg.gif" alt="Loading..."/>
      </div>

    </div>
  {% endblock %}
  </div>
</div>

#2修改dashboard.html

从容器中取出display:none-液体内部dashboard.html

<!-- show container when loaded -->
<div class="container-fluid">

  <div id="ajax-content"></div>
  <!-- other contents -->

</div>

#3更新body.html中的loadDashboard

function loadDashboard() {
    // Remove all the spinner JavaScript
    const container = document.getElementById('dashboard-container');

    fetch('{% url "erp:dashboard_graphs" %}')
        .then(response => response.text())
        .then(html => {
                // spinner will be remove by innerHTML
                container.innerHTML = html;                    
                })
    .catch(error => {
            console.error('Error loading dashboard:', error);
            // possibly empty the container to remove the spinner?
            });
}

总结:

  1. body.html加载渲染的微调器,并开始提取
    1.当fetch完成时,dashboard.html将覆盖微调器-删除它
  2. dashboard.html默认可见,因此将默认显示

相关问题