Sunday, January 8, 2017

Django - 021 - Rendering a Template

Once you have a Template object, you can pass it data by giving it a context. A context is simply a set of template variable names and their associated values. A template uses this to populate its variables and evaluate its tags. a context is represented in Django by the Context class, which lives in the django.template module. Its constructor takes one optional argument: a dictionary mapping variable names to variable values.

Call the Template object's render() method with the context to fill the template:

 ~/Documents/my_d3_project/django/myD3site $ python manage.py shell
Python 2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 17:02:03) 
Type "copyright", "credits" or "license" for more information.

IPython 3.2.0 -- An enhanced Interactive Python.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from django.template import Context, Template

In [2]: t = Template("My name is {{name}}.")

In [3]: c = Context({'name':'Basavaraj'}) 

In [4]: t.render(c)
Out[4]: u'My name is Basavaraj.'

In [5]: 

A special Python prompt:
If you have used Python before, you maybe wondering why we are running python manage.py shell instead of just python (or python3). Both commands will start the interactive interpreter, but the manage.py shell command has one key difference: before starting the interpreter, it tells Django which settings file to use.

Many parts of Django, including the template system, rely on your settings and you won't be able to use them unless the framework knows which settings to use.

If you are curious, here is how it works behind the scenes. Django looks for an environment variable called DJANGO_SETTINGS_MODULE, which should be set to the import path of your settings.py. For example, DJANGO_SETTINGS_MODULE might be set to 'myD3site.settings', assuming myD3site is on your Python path.

When you run python manage.py shell, the command takes care of setting DJANGO_SETTINGS_MODULE for you. You will need to use python manage.py shell in these examples or Django will throw an exception.

No comments:

Post a Comment