Django has Template System for Display Content on Web. Using Views and Django Template we can display data in the template. There are lots of Django Template Tags and Filter for displaying data dynamically. We can pass the Model data to view for rendering it in the template.
In this tutorial, you will learn how to display data in templates. How to use different template tags and filter for dynamic render data. Display data from the model/database and display it. How to pass variables and context from views to the Django template system.
How to Pass Context from View to Template
We will be using generic views for passing data to a template. You can different generic views like ListView, DetailView, View, etc. And with those generics views, you can use different methods like get, get_context_data, get_queryset.
In this example, I am using ListView to display Post Model Data. I am passing the object name as post to blog.html. We can access the context using the pass object name.
# views.py from django.views import generic from .models import Post class PostView(generic.ListView): template_name = 'blog.html' model = Post context_object_name = "post"
# urls.py from django.contrib import admin from django.urls import path from blog_app.views import PostView urlpatterns = [ path('admin/', admin.site.urls), path('', PostView.as_view(), name='post'), ]
How to Render Variable and Context in Django Template
Django template dynamic variable name. Now that we have passed the context, we need to display that data. We will be using for loop in the template as it is queryset.
{% for blog in post %} {{blog.post_title}} {{blog.post_body}} {{blog.post_author}} {{blog.post_date}} {% endfor %}
Note – post_title
, post_body
, post_author
, post_date
are fields in Post
Model.
For example, our template (blog.html) will look like this –
{% extends 'base.html' %} {% load static %} {% block content %} <div class="col-sm-8"> {% for blog in post %} <h2>{{blog.post_title}}</h2> <small>Posted by {{blog.post_author}} on {{blog.post_date}}</small> <br><br> <p>{{blog.post_body}}</p> <br> <hr /> <br> {% endfor %} </div> {% endblock content %}
You can learn more about Built-in Tags and Built-in Filters.
GitHub – Run Example Locally
It is also available on GitHub – https://github.com/studygyaan/How-to-Render-Dynamic-Data-in-Django-Template
Clone the Repository –
git clone https://github.com/studygyaan/How-to-Render-Dynamic-Data-in-Django-Template.git
Change Directory
cd How-to-Render-Dynamic-Data-in-Django-Template
Create Virtual Environment
virtualenv env
Activate Virtual Environment
source env/bin/activate
Run requirement.txt file to install libraries using Pip3
pip3 install -r requirements.txt
Run the server
python3 manage.py runserver
And open http://localhost:8000/ in your browser.
You have learned to – pass data to template django, django pass data to template, django views render template, django create table dynamically, display data from database in django