The following article demonstrates Context Objects in Django.

In Django, context objects are used to pass variables from views to templates. Here’s an example of how to create and manipulate context objects in Django.

  1. Create a new Django app inside your project.
python manage.py startapp myapp
  1. Open the “views.py” file inside your app’s directory, and add the following code.
from django.shortcuts import render
from datetime import datetime

def my_view(request):
    my_date = datetime.now()
    my_list = ['apple', 'banana', 'cherry']
    my_dict = {'name': 'John', 'age': 30}
    context = {
        'my_date': my_date,
        'my_list': my_list,
        'my_dict': my_dict,
    }
    return render(request, 'my_template.html', context)

This defines a new view named “my_view” that creates a context dictionary with three variables: “my_date”, “my_list”, and “my_dict”. “my_date” is set to the current date and time using the datetime.now() method. “my_list” is a simple list of strings, and “my_dict” is a dictionary with two keys, “name” and “age”.

  1. Create a new file called “my_template.html” inside your app’s “templates” directory, and add the following code.
<!DOCTYPE html>
<html>
<head>
    <title>My Template</title>
</head>
<body>
    <h1>My Date</h1>
    <p>{{ my_date }}</p>
    <h1>My List</h1>
    <ul>
        {% for item in my_list %}
        <li>{{ item }}</li>
        {% endfor %}
    </ul>
    <h1>My Dictionary</h1>
    <dl>
        {% for key, value in my_dict.items %}
        <dt>{{ key }}</dt>
        <dd>{{ value }}</dd>
        {% endfor %}
    </dl>
</body>
</html>

This is a simple HTML template that uses Django’s template language to display the values of the three variables in the context dictionary.

  1. Finally, add a URL pattern for your new view in your project’s “urls.py” file.
from django.urls import path
from myapp.views import my_view

urlpatterns = [
    path('my-url/', my_view, name='my_url'),
]

This maps the URL “/my-url/” to your new view.

Now you can run your Django development server and visit the URL “/my-url/” to see your template in action! The placeholders in the template will be replaced with the values from the context dictionary, and you should see the current date and time, a list of three fruits, and a dictionary with a name and an age.


Further Reading

Introduction to Django Framework and its Features

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com