Open In App

Display the Current Year in a Django Template

Last Updated : 23 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this simple project, we demonstrated how to display the current year in a Django template. By using the datetime module in Python, we passed the current year to the template context, which allowed us to display it in the HTML. This method can be applied to various dynamic content needs in Django projects.

Project Overview to Display the Current Year in a Django Template

We'll create a small Django project with a single app. The app will have a template that shows the current year. Here’s a step-by-step guide:

1. Setting Up the Django Project

First, ensure you have Django installed. You can install it using pip if you haven’t already:

pip install django

Create a new Django project:

django-admin startproject myproject
cd myproject

Create a new Django app:

python manage.py startapp myapp

2. Configure Your Project

Open myproject/settings.py and add 'myapp' to the INSTALLED_APPS list:

INSTALLED_APPS = [
...
'myapp',
]

3. Create a View

In myapp/views.py, create a view to render the template:

Python
from django.shortcuts import render
from datetime import datetime

def index(request):
    current_year = datetime.now().year
    return render(request, 'index.html', {'current_year': current_year})

4. Create a Template

Create a directory named templates inside the myapp directory. Within templates, create a file named index.html. Add the following content to index.html:

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Current Year</title>
</head>
<body>
    <footer>
        <p>&copy; {{ current_year }} My Company</p>
    </footer>
</body>
</html>

5. Configure URL Routing

Open myproject/urls.py and include your app's URLs:

Python
from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
]

6. Run the Development Server

Now, run the development server to see the changes:

python manage.py runserver

Navigate to http://127.0.0.1:8000/ in your web browser. You should see the footer displaying the current year dynamically.

Capture


Next Article
Practice Tags :

Similar Reads