Course Content
Django: First Dive
Django: First Dive
2. Write the First Page
4. Working with Database
Context
As mentioned earlier, DTL allows the opportunity to generate HTML pages dynamically. This means we can use Python values and variables in HTML pages that will be inserted before sending them to the user (client).
The data passed to the HTML page is called Context, and we will learn how to pass it.
Context is a dict
that contains keys (parameter names) and values.
Context in Views
Let's improve our hello_world_view
function and HTML page to display the current date:
Inside the view function, there is a dictionary called payload
that contains a single key-value pair. The key is "date"
, and its corresponding value is the current date obtained using datetime.now().date()
. datetime.now()
returns the current date and time, and .date()
extracts only the date part from it.
The payload
dictionary is then passed as the context
parameter to the render()
function, along with other parameters. The render()
function is a Django shortcut that combines a given template with a given context dictionary and returns an HttpResponse
object with the rendered content.
Note
- The
payload
dictionary can be named anything else.- The
context
parameter in therender()
function is the third optional argument and you can pass it without keyword.
Context in Templates
We need to use specific syntax to access context in the HTML templates. This specific syntax is designed to not interfere with writing HTML code.
To access data from context, we need to use {{ parameter_name }}
inside the template file (hello_world.html
in our case).
The {{ date }}
syntax will display the value of the "date"
key in the context
dictionary as a string.
Everything was clear?