1.
Current Time Display
Description: Create a web page that displays the current date and time.
Key Concepts:
• URL routing
• Views
• Templates
• Python’s datetime module
Features:
• Display formatted current date and time.
• Optionally, update the time dynamically using JavaScript for real-time updates.
1. views.py (in timeapp):
This le will de ne the view to get the current time.
from django.http import HttpResponse
from django.shortcuts import render
import datetime
def current_time(request):
now = datetime.datetime.now() # Get the current date and time
return render(request, 'timeapp/current_time.html', {'current_time': now})
fi
fi
2. urls.py (in timeapp):
De ne the URL pattern for the time display page.
from django.urls import path
from . import views
urlpatterns = [
path('time/', views.current_time, name='current_time'),
3. urls.py (in project folder):
Include the app’s URLs in the project’s main URL con guration.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('timeapp.urls')), # Include timeapp
URLs
]
4. current_time.html (in templates/timeapp/):
Create the HTML template that displays the current time. Optionally, use JavaScript to update the
time dynamically.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Current Time</title>
<!-- Bootstrap CDN -->
fi
fi
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/
Jr59b6EGGoI1fFkwKwP9k9a2 " crossorigin="anonymous">
</head>
<body>
<div class="container text-center mt-5">
<h1 class="display-4">Current Date and Time</h1>
<p class="lead">{{ current_time }}</p>
</div>
</body>
</html>
5. Run the Server:
Once everything is set up, you can run the Django server:
python manage.py runserver
Visit http://127.0.0.1:8000/time/ in your browser to see the current date and time
displayed, styled with Bootstrap.
fl