Django Program: Dynamic Data Loading in Template
Goal:
When a user visits the page, the current time will be displayed dynamically. The time will refresh
(change) each time the page is loaded.
Step 1: Project Setup
django-admin startproject mysite
cd mysite
python manage.py startapp demo
Step 2: Register App
In mysite/settings.py, add:
INSTALLED_APPS = [
...
'demo',
Step 3: Define URL
In mysite/urls.py:
from django.contrib import admin
from django.urls import path
from demo import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.show_time, name='show_time'), # Main page
]
Step 4: Create View
In demo/views.py:
from django.shortcuts import render
from datetime import datetime
def show_time(request):
current_time = datetime.now()
context = {'time': current_time}
return render(request, 'demo/time.html', context)
Step 5: Create Template
Create folder: demo/templates/demo/time.html
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Data Example</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Current Server Time: {{ time }}</p>
</body>
</html>
Step 6: Run Server
python manage.py runserver
Visit: http://127.0.0.1:8000/
Each time you refresh the page, the time updates - this shows dynamic data loading on each page
view.
Key Concepts:
- views.py: Pass dynamic data using context.
- Template: Access dynamic variables using {{ variable_name }}.
- Every page load - function executes again - data refreshes.