如何在Django中将视图中的数据值传递给模板?

时间:2017-08-25 09:17:30

标签: javascript jquery ajax django python-3.x

目前,我有两个模板: no_results_tickets.html results_tickets.html 。第一个模板包含两个下拉菜单,用于选择年份和周数,因此一旦您点击提交按钮,Web应用程序将从Web API查找所选周和年的票证,然后在另一个模板中显示结果。

Drop down menus

我现在缺少的是如何在第二个模板中显示这些结果。

这是我到目前为止所做的。

forms.py

class DropDownMenuForm(forms.Form):
    week = forms.ChoiceField(choices=[(x,x) for x in range (1,53)])
    year = forms.ChoiceField(choices=[(x,x) for x in range (2016,2021)])

模板no_results_tickets.html

<h3>Please, select the year and week number to retrieve the data.</h3>
<form id="search_dates" method="POST" action="/results_tickets/"> {% csrf_token %}
<h6>Select year</h6>

<div class="row">
    <div class="col-sm-8">
        <select name="select_year">
            <option value = {{form.year}}></option>
        </select>
    </div>
    <div class="col-sm-8">
        <h6>Select week</h6>
        <select name="select_week">
            <option value= {{form.week}}></option>
        </select>
        <button type="submit">Search</button>
    </div>
</div>
</div>

urls.py

url(r'^no_results_tickets/$',views.tickets_results_test, name='no_results_tickets'),
url(r'^results_tickets/$',views.tickets_results_test, name='results_tickets'),

查看

@api_view(['GET','POST',])
def tickets_results_test(request):

    if request.method == "GET":
        ''' Template for displaying the dropdown menus.'''
        template_name = 'personal_website/no_results_tickets.html'
        form = DropDownMenuForm()
        return render(request, template_name, {'form': form})

    elif request.method == "POST":

        template_name = 'personal_website/results_tickets.html'
        year = request.POST.get('select_year', None)
        week = request.POST.get('select_week', None)
        # ... do stuff ....

        data = {"labels":days, "days_of_data": count_data}
        return render(request, template_name, data)

结果在我的控制台中给出,但我希望他们在results_tickets.html模板中看到。 我缺少的是从数据字典中检索内容的技能,因此我可以在第二个模板中获取值并绘制图形。

模板results_tickets.html

<script>
{% block jquery %}

//I tried to get the content of the dict data with the following code but I was unsuccessful
var days_of_data = []
var label_number_days = []
days_of_data = data.count_data
label_number_days = data.days


function setChart(){
var ctx_tickets_per_day       = document.getElementById("tickets_per_day")

var tickets_per_day = new Chart(ctx_tickets_per_day, {
    showTooltips: false,
    type:'bar',
    data: {
        labels: label_number_days,
        datasets :
            [{
                label: 'User 01',
                data: [days_of_data[0],days_of_data[1],days_of_data[2],days_of_data[3],days_of_data[4],days_of_data[5],days_of_data[6]],
                backgroundColor: 'rgba(255, 99, 132, 0.6)',
                borderColor: '#777',
                borderWidth: 1,
                hoverBorderWidth: 3,
                hoverBorderColor: '#000'
            },
            { ....//graph the values for the rest of users}
    })
}

{% endblock %}
</script>
{% block content %}

<div class ='row'>
<div class="col-sm-12" url-endpoint='{% url "tickets_per_day_results" %}'>
        <div>
            <canvas id="tickets_per_day" width="800" height="500"></canvas>
        </div>
</div>
</div>
{% endblock content %}

1 个答案:

答案 0 :(得分:1)

也许您只是错过{{ }}周围的django标记data? 你也可能需要将python字典转换为json字符串才能在js中使用它:

views.py 中修改为:

import json
...
data = {"labels":days, "days_of_data": count_data}
my_data = {'my_data': json.dumps(data)}
return render(request, template_name, my_data)

如果您要添加模板results_tickets.html

<script>
{% block jquery %}


var days_of_data = []
var label_number_days = []
var data = {{my_data|safe}}
days_of_data = data.count_data
label_number_days = data.days

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

它可能有效