My goal is to write dynamically some urls of images in the HTML page. Urls are stored in a database.
To do so, first I am trying to render a simple varable in a template. Reading the docs and other sources, it should be done in 3 steps:
For the configuration: in settings.py
TEMPLATES = [
{
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
…
'django.template.context_processors.request',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages', ],
},
},
]
The variable name in the template: In MyHTMLFile.html is foo
…
<td>MyLabel</td><td><p>{{ foo }}</p></td><td>-----------</td>
…
in the view.py, one of the lines
myvar1 ="BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
context = {foo: myvar1,}
return render_to_response("MyHTMLFile.html", context, context_instance = RequestContext(request) )
return render(request, 'MyHTMLFile.html', {foo: myvar1})
return render_to_response("MyHTMLFile.html", context , context_instance=RequestContext(request) )
return render(request, 'MyHTMLFile.html', context)
The html page is well rendered, but no data in the html table.
Do you have an idea ? I am curious to know what i misunderstand.
Regarding the versio, i am using: python: Python 2.7.13 django: 1.10.5
Thank you
context = {foo: myvar1,}
This should give you a NameError
unless ofcourse you have a variable named foo
in which case it may or may not hold a string foo
. So in short you are not sending the right data to the template. It should be
context = {'foo': myvar1,}
And then
return render_to_response("MyHTMLFile.html", context, context_instance = RequestContext(request) )
# Below this line code will not be executed.
return render(request, 'MyHTMLFile.html', {foo: myvar1})
return render_to_response("MyHTMLFile.html", context , context_instance=RequestContext(request) )
return render(request, 'MyHTMLFile.html', context)
note that the return
keyword returns from the function. Code after that doesn't get executed.
lastly render_to_response is deprecated. render
is the current function to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With