How to Add Data from Queryset into Templates in Django
Last Updated :
16 Apr, 2024
In this article, we will read about how to add data from Queryset into Templates in Django Python. Data presentation logic is separated in Django MVT(Model View Templates) architecture. Django makes it easy to build web applications with dynamic content. One of the powerful features of Django is fetching data from a database and show on web pages.
Querysets serve as a powerful tool for retrieving data from databases and integrating data from the database. Integrating Querysets data into the templates is essential for displaying the dynamic data on the web pages.
Add Data from Queryset into Templates in Python Django
Below is the implementation to add data from the query set into templates in Django and Python:
Starting the Project Folder
To start the project use this command
django-admin startproject library
cd library
To start the app use this command
python manage.py startapp book
Now add this app to the ‘settings.py’
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'book'
]
File Structure
.png)
Setting Necessary Files
models.py : After the initial project setup, we create a Book Model inside the book app. Book models have price, name, and author fields.
Python3
# Create your models here.
# book/models.py
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=100)
author = models.CharField(max_length=100)
price = models.IntegerField()
def __str__(self):
return self.name
views.py : Django code defines a view function named All_Book
that fetches all Book
objects from the database using Django's ORM (Book.objects.all()
) and passes them to a template named 'index.html' via the render
function, making them available as queryset
in the template.
Python3
# Create your views here.
# book/views.py
from django.shortcuts import render
from .models import Book
def All_Book(request):
queryset = Book.objects.all()
return render(request, 'index.html', {'queryset': queryset})
library/urls.py: Below, are the Project urls.py file.
Python3
from django.contrib import admin
from django.urls import path
from book.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('', All_Book),
]
admin.py : Here we are registering our models.
Python3
# admin.py
from django.contrib import admin
from .models import Book
admin.site.register(Book)
Creating GUI
index.html : HTML and CSS code creates a webpage layout for a book store, featuring a centered container with a heading "My Book Store" and a list of books with their names and authors, likely to be populated dynamically using a templating language like Django's template engine (indicated by {% for item in queryset %}
).
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Book store</title>
</head>
<body>
<h1>My Book</h1>
<ul>
{% for item in queryset %}
<li>{{ item.name }} - {{ item.author }}</li>
{% endfor %}
</ul>
</body>
</html>
Deployment of the Project
Run these commands to apply the migrations:
python3 manage.py makemigrations
python3 manage.py migrate
Run the server with the help of following command:
python3 manage.py runserver
Output:
Add Data from Queryset into Templates in Django PythonVideo Demonstration
Similar Reads
How to Perform Query Filtering in Django Templates
Sometimes we may want to filter or modify the list of objects within the template itself to tailor the data being displayed. While filtering should generally be done at the view level for clarity and separation of concerns, Django templates provide some basic filtering capabilities through template
5 min read
How to get JSON data from request in Django?
Handling incoming JSON data in Django is a common task when building web applications. Whether you're developing an API or a web service, it's crucial to understand how to parse and use JSON data sent in requests. In this article, we will create a simple Django project to demonstrate how to retrieve
2 min read
How to do a not equal in Django queryset
In Django, filtering data from the database is typically done through QuerySet methods provided by Djangoâs ORM (Object Relational Mapping). When you need to filter records where a certain field is not equal to a specific value, Django offers an elegant way to handle this using the exclude() method
4 min read
How to Convert a Django QuerySet to a List?
Converting a Django QuerySet to a list can be accomplished using various methods depending on your needs. Whether you want a list of model instances, specific fields, IDs, or serialized data, Django provides flexible ways to achieve this. Understanding these methods will help you effectively work wi
3 min read
Access Constants in settings.py from Templates in Django
Django is a popular web framework known for its simplicity and powerful features, enabling developers to build robust web applications quickly. One of the essential components of a Django project is the settings.py file, where configuration constants such as database settings, static files, and othe
4 min read
How to perform OR, AND and NOT in Django QuerySet Filtering
We can use the Q objects in django.db.models to create an OR, AND, and NOT filter in a Django query. The Q objects are used to form complex filtering by joining several conditions through logic operators like OR, AND, and NOT. In this article, we will learn to perform AND, OR, and NOT filters while
4 min read
How to Convert Models Data into JSON in Django ?
Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database SQLlite3, etc. How to Convert Models
2 min read
How to Check for Last Loop Iteration in Django Template
Iterating over lists or querysets is a common task when working with Django templates. Sometimes, we may need to perform a specific action or modify the output during the last iteration of a loop. Unlike in Python, where checking for the last iteration is straightforward using loop indices, Django t
5 min read
Format Numbers in Django Templates
Formatting numbers in Django templates is essential for creating a polished and user-friendly interface. Whether you use Djangoâs built-in filters for common formatting needs, create custom filters for specific requirements, or leverage third-party libraries for advanced options, Django provides the
2 min read
How to create Custom Template Tags in Django ?
Django offers a variety of built-in template tags such as {% if %} or {% block %}. However, Django also allows you to create your own template tags to perform custom actions. The power of custom template tags is that you can process any data and add it to any template regardless of the view executed
4 min read