Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Context | Templates
Django: First Dive
course content

Contenido del Curso

Django: First Dive

Django: First Dive

1. Get Started
2. Write the First Page
3. Models
4. Working with Database
5. Templates
6. Request Handling

bookContext

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 the render() 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.

What is a context?

What is a context?

Selecciona unas respuestas correctas

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 5. Capítulo 2
We're sorry to hear that something went wrong. What happened?
some-alt