Pass Data From Django View to TemplateTo pass data from a Django view to a template, you can use the render() function along with a dictionary containing the data you want to pass.
- Define your view function:
from django.shortcuts import renderdef my_view(request):
data = {
‘message’: ‘Hello, world!’,
‘items’: [‘apple’, ‘banana’, ‘orange’]
}
return render(request, ‘my_template.html’, data) - Access the data in the template:
In your template (my_template.html), you can access the data using template variables.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>My Template</title>
</head>
<body>
<h1>{{ message }}</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
from django.shortcuts import render
def my_view(request):
my_list = [‘apple’, ‘banana’, ‘orange’]
return render(request, ‘my_template.html’, {‘my_list’: my_list})
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>My Template</title>
</head>
<body>
<h1>Fruits</h1>
<ul>
{% for fruit in my_list %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
</body>
</html>
{% for fruit in my_list %} iterates over each element in the my_list and {% endfor %} marks the end of the loop. Within the loop, {{ fruit }} displays each item in the list
use the {% if %} and {% else %} template tags to conditionally display different content
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Authentication Status</title>
</head>
<body>
{% if user_authenticated %}
<h1>Welcome, {{ request.user.username }}!</h1>
<p>You are logged in.</p>
{% else %}
<h1>Welcome, Guest!</h1>
<p>You are not logged in. Please <a href=”{% url ‘login’ %}”>log in</a>.</p>
{% endif %}
</body>
</html>
In this example:
- If the user is authenticated (user_authenticated is True), it will display a welcome message with the username and a message indicating that the user is logged in.
- If the user is not authenticated (user_authenticated is False), it will display a generic welcome message for guests and provide a link to the login page.
set up the static directory
- Create a static directory:
myproject/
├── myapp/
│ ├── migrations/
│ ├── templates/
│ └── …
├── static/ <– Create this directory
└── … - Configure STATICFILES_DIRS setting: In your Django settings file (settings.py), configure the STATICFILES_DIRS setting to include the path to the static directory you created. This tells Django where to find your static files during development
STATICFILES_DIRS = [
BASE_DIR / “static”,
] - Load static files in templates: In your HTML templates, load static files using the {% load static %} template tag and reference the static files using the {% static %} template tag.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>My Website</title>
<link rel=”stylesheet” href=”{% static ‘css/style.css’ %}”>
</head>
<body>
<img src=”{% static ‘images/logo.png’ %}” alt=”Logo”>
<script src=”{% static ‘js/script.js’ %}”></script>
</body>
</html>
To create a fixed header and footer in a Django HTML template using the {% include %} template tag.
- Create Header and Footer HTML files:
<header>
<h1>This is the header</h1></header>
<footer>
<p>© 2024 My Website. All rights reserved.</p></footer>
- Include Header and Footer in the Base Template: Create a base HTML template that will serve as the main template for your website layout. Use the {% include %} template tag to include the header and footer HTML files.
base.html:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>{% block title %}My Website{% endblock %}</title></head>
<body>
{% include ‘header.html’ %}<main>
{% block content %}{% endblock %}
</main>{% include ‘footer.html’ %}
</body>
</html> - Extend Base Template in Other Templates: In your other templates, extend the base template (base.html) and override the {% block content %} with the specific content for each page.
home.html (example):
{% extends ‘base.html’ %}{% block title %}Home | My Website{% endblock %}
{% block content %}
<h2>Welcome to the home page!</h2>{% endblock %}
In Django, URL template tags are used to generate URLs for views within your Django project. They provide a way to create dynamic URLs in your HTML templates without hardcoding them, allowing for more flexible and maintainable code. The two main URL template tags in Django are {% url %} and {% static %}
- Defining URL patterns:
from django.urls import path
from . import viewsurlpatterns = [
path(‘home/’, views.home, name=’home’),
path(‘about/’, views.about, name=’about’),]
- Using URL template tags in templates:
<a href=”{% url ‘about’ %}”>About Us</a>
<img src=”{% static ‘images/logo.png’ %}” alt=”Logo”>
Source: hashnode.com