abautista
abautista

Reputation: 2780

How to pass data values from Views to Templates in Django?

Currently, I have two templates: no_results_tickets.html and results_tickets.html. The first template contains two drop-down menus that are used to select the year and the number of week, so once you hit the submit button, the web app looks for the tickets for the selected week and year from the Web API and then it displays the results in another Template.

Drop down menus

What I am missing right now is how to display these results in the second Template.

This is what I have so far.

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)])

template 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'),

View

@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)

The results are given in my console but I want them to see in the results_tickets.html template. What I am missing is the skill to retrieve the contents from the data dictionary, so I can get the values and graph them in this second template.

template 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 %}

Upvotes: 1

Views: 2937

Answers (1)

BartDur
BartDur

Reputation: 1106

Maybe you are just missing the django tag {{ }} around data? Also you probably need to convert the python dictionary to a json string to be able to use it in js:

In views.py modify to:

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

If you would add to the template 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>

it might work

Upvotes: 1

Related Questions