In this Python Django tutorial, you will learn about outputting Python to HTML in Django, where you will learn how to write Python-like code on your HTML page.
Also, I will explain to you “What is the Django template system and its components?” because the Django template system is a way to output Python to HTML in Django.
Additionally, you will understand different template tags that you can use in your HTML page to output the Python data.
Outputting Python to HTML in Django
Django provides a feature called template engine, this template engine allows developers to mix HTML with Python code. In simple terms, using a template engine you can write a python code in your HTML or template.
In general, if you have data and you want to use Python code to render that data with HTML then you can do that with the help of a template tag in Django.
In other words, if you pass data from your Django view and want to output or display that data on your webpage then you can do that by using the template tag. So template system in Django allows you to write a Python-like syntax in your HTML page.
But ‘What is the purpose of writing Python syntax within html page’, the purpose is very simple, it allows to maintain a clear separation between business logic (Python code) and presentation logic(template or HTML).
So you learned about three words here, Django engine, Django template tag, and Django template system.
- The Django template tag and template engine is the component of the Django template system. The Django template engine processes templates or HTML and produces the output.
- Whereas the Django template tag is a particular piece of syntax that is used in the Django template to perform some operations. It is enclosed within ‘{% %}’ or ‘{{ }}’, within these curly braces you write the Python code such as if statement, loop, etc.
The template tag you use in your template or HTML page for outputting the Python data or code. For example, you can write the HTML with Python like this <p> {% if a > b %}</p>.
Outputting Python to HTML in Django Project Setup
Now you know about the Django template system and a little overview of how you can output Python to an HTML page.
Here set up a Django project to learn about how to output Python to HTML in Django. So follow the below steps:
First, open your terminal or command prompt and create a virtual environment named ‘env’.
python -m venv env
Activate the environment.
env\Scripts\activate
Install the latest version of Django using the below command.
pip install django
Create a Django project named ‘django_output’ using the below code.
django-admin startproject django_output
Change the directory to Django project ‘django_output’.
cd django_output
Create a Django app named ‘python_html’.
python manage.py startapp python_html
Open the project in Visual Studio Code or your preferred IDE.
Now open the setting.py file of your Django project ‘django_output’ and add the Django app ‘python_html’ in the INSTALLED_APPS list as shown below.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'python_html'
]
Then open the urls.py file of your Django app and add the following URL path.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('python_html.urls')),
]
Then open the admin.py file of your Django app ‘python_html’ and add the following lines of code.
from django.contrib import admin
from .models import Product
# Register your models here.
admin.site.register(Product)
Now you have configured your project.
Outputting Python to HTML in Django Model and View
Open the models.py file of your Django app ‘python_html’ and add the following lines of code.
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.FloatField()
stock = models.IntegerField()
In the above define the model named Product with field lists name, price, and stock of type CharField, FloatField, and IntegerField respectively.
Now open the views.py file of your Django app ‘python_html’ and add the following lines of code.
from django.shortcuts import render, get_object_or_404
from .models import Product
def product_detail(request):
product = None
if request.method == 'POST':
product_name = request.POST.get('product_name')
product = get_object_or_404(Product, name=product_name)
return render(request, 'product.html', {'product': product})
In the above code from lines 4 to 9 define the function view named ‘Product’ that accepts parameters for a request object.
After that in line 5, define the variable product and assign the None value to it. Then check if the incoming request is POST method, if it is POST method then perform the following operations:
- At line 7 retrieve the value that comes with the request in the variable ‘product_name’ using the request.POST.get(‘product_name’) method.
- Then at line 8 reteriving the ‘Product’ object based on the provided product_name using the function get_object_or_404().
The get_object_or_404() returns the product if a product with that name exists, otherwise, it raises the Http404 exception and the Django will show an error 404 “Not Found” page.
The function get_object_or_404(Product, name=product_name) takes two argument:
- First is the Product model that represents the product in the database.
- Second is the keyword argument specifying that filtering the ‘Product’ model’s object by their name attribute.
Then at line 9 render the template ‘product.html’ and pass the reterive product as a dictionary to the template.
Outputting Python to HTML in Django Template
Now create a templates folder in your Django project and within that folder create an HTML file called product.html and in the product.html file add the following lines of code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search Product</title>
</head>
<body>
<form method="post">
{% csrf_token %}
<label for="product_name">Enter Product Name:</label>
<input type="text" id="product_name" name="product_name" required>
<input type="submit" value="Search">
</form>
{% if product %}
<div class="product-detail">
<h1>{{ product.name }}</h1>
<p>Price: ${{ product.price }}</p>
<p>Stock: {{ product.stock }}</p>
</div>
{% endif %}
</body>
</html>
Here you need to know about template tags in Django to write HTML with Python code. So here from lines 17 to 23 outputting the product details using the Python code within curly braces { }.
When you write something like this {% if product%} in your template, then it means you are using a template tag in your Django template.
Django provides different kinds of template tags, Let’s know about some of them:
- First is the conditional statement, you can run conditional statements in your template. The syntax is given below.
{% if condition %}
//render html code
{% else %}
//otherwise render this code
{% endif %}
Suppose you are passing some variable value through context to the template you can that variable within the template. For example, the user you are passing the user details from your template view.
You can think that the user is an object which is passed to the template through view and it has some properties like name, and dob that you can use in the template to output the user name and date of birth.
Then you can check the existence of the user using the tag {% if user %} which means if the user exists, then execute the if part otherwise execute the {% else%} part and the last stage is {% endif %} which means the end of if statement.
Look at the below code.
{% if user%}
<p> Welcome you logged in </p>
{% else %}
<p> User doesn't exist <p>
{% endif %}
- Now think that the user contains some information like user name, dob, etc. To access that value or data from the user object as shown below.
{% if user%}
<p> Welcome {{user.name}} </p>
{% else %}
<p> User doesn't exist <p>
{% endif %}
So here in the above code access the user name using {{user. name}} which means whenever you want to output the object value always use the double curly braces {{}}.
To access the user’s date of birth, you can write the tag like this {{user.dob}} and this is the second type of tag in Django.
If you want to know more about the Django template tag, then refer to the tutorial If statement in the Django template
Now let’s know about what’s happening in our code which is shown below.
<form method="post">
{% csrf_token %}
<label for="product_name">Enter Product Name:</label>
<input type="text" id="product_name" name="product_name" required>
<input type="submit" value="Search">
</form>
{% if product %}
<div class="product-detail">
<h1>{{ product.name }}</h1>
<p>Price: ${{ product.price }}</p>
<p>Stock: {{ product.stock }}</p>
</div>
{% endif %}
From lines 10 to 15 define the form to accept the input from the user. The user types the product name in the input box and clicks on the submit button.
- After submitting the form, the request is made to view product_detail that you have defined above.
- Based on the provided product name view passes the object of that product containing details such as product name, price, and stock to the template ‘product.html’.
Then the template code from 17 to 23 gets executed because the conditional tag {% if product %} becomes true. As soon as it becomes true, it outputs the product name, price, and stock using {{product.name}}, {{product.price}} and {{product.stock}} respectively.
Now you know how to write the Python-like code in your template to output the values from the view in your HTML page.
Outputting Python to HTML in Django Migration and URL
Create a new file urls.py in your Django app ‘python_html’ and add the following URL path.
from django.urls import path
from . import views
urlpatterns = [
path('product/', views.product_detail, name='product_detail'),
]
After that open your terminal and run the following commands one by one to migrate the model that comes with Django.
python manage.py makemigrations
python manage.py migrate
Outputting Python to HTML in Django Running Server
Now run the following command in your terminal to run the Django server.
python manage.py runserver
After running the server open your browser and type the URL ‘http://127.0.0.1:8000/product/’ and you will see the page as shown below.
Now type the product name in the search box such as ‘laptop’ and click on the search button. I have already added some products through the Django admin panel, If you haven’t added them, add them to your database.
If you want to know how to set up an admin panel, then refer to the tutorial Python Django to get an admin password.
As soon as you click on the search button, you see the product details such as name, price, and stock as shown below.
In the above output, you can see that how product details are output on the HTML page such as name, price, and stock using the template tag in Django.
So using the template tag in your template or HTML you can write Python-like code but not pure Python code to output the Python data to the HTML page.
Conclusion
In this Python Django tutorial, you learned how to output the Python data to HTML in Django. Also learned about the Django system, template engine, and tag. Finally, you learned how to use the Django template tag to output the Python data to an HTML page.
Also, take a look at some more Django tutorials.
- Python Django filter
- Python Django get
- Django for loop
- Setup Django project
- Python Django gets enum choices
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.