Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a list from a view to template in django

Tags:

python

django

I am trying pass to list from a view to template in Django.

In my file wiew.py I define the view named hour

# This Python file uses the following encoding: utf-8

from django.shortcuts import render
from django.http import HttpResponse
from datetime import datetime 
from django.shortcuts import render_to_response

# Create your views here.
def hour(request):
now = datetime.now()
list = ['Bern','Bob','Eufronio','Epifanio','El pug']
return render_to_response('hour.html',list)

I'm using shorcuts in my view.

I have a template named hour.html so this way:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8">
    <title>Date</title>

</head>
<body>
    The names are:
    {%for item in list%}
        <li>{{item}}</li>
    {% endfor %}
</body>
</html>

But my template hour.html is showed empty in the browser. How to can I send the list from my view to template. Thanks for tour attention

like image 637
bgarcial Avatar asked Feb 28 '14 23:02

bgarcial


People also ask

How do you pass variables from Django view to a template?

And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {{ NAME }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What is {% block content %} in Django?

Introducing {% block %}The block tag is used to define a block that can be overridden by child templates. In other words, when you define a block in the base template, you're saying that this area will be populated with content from a different, child template file.


Video Answer


2 Answers

You should use return render_to_response('hour.html',{"list": list})

Or return render(request, 'hour.html', {"list": list})

The second render need from django.shortcuts import render

like image 107
virusdefender Avatar answered Nov 03 '22 02:11

virusdefender


list is a python built-in sequence type, you should avoid using generic names for you variable names to avoid conflicts. You can read more about Python's built-in types here.

For this however, you just need to pass in the context:

return render_to_response('hour.html', {"list": list})
like image 42
Drewness Avatar answered Nov 03 '22 01:11

Drewness