0
0
Djangoframework~30 mins

Template filters (date, length, default) in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Django Template Filters: date, length, default
📖 Scenario: You are building a simple Django web page to display a list of events. Each event has a name, a date, and an optional description.Sometimes the description might be missing, and the date should be shown in a friendly format. You also want to show how many events are in the list.
🎯 Goal: Create a Django template that uses the date, length, and default filters to display event information clearly and handle missing descriptions gracefully.
📋 What You'll Learn
Create a list of events with exact data
Add a variable to count events
Use the date filter to format event dates
Use the default filter to show a fallback description
Use the length filter to show the number of events
💡 Why This Matters
🌍 Real World
Displaying event information on websites is common. Using template filters helps format data cleanly and handle missing information gracefully.
💼 Career
Knowing how to use Django template filters is essential for backend web developers working with Django to create user-friendly web pages.
Progress0 / 4 steps
1
Create the events list
Create a Python list called events with these exact dictionaries: {'name': 'Concert', 'date': datetime.date(2024, 7, 20), 'description': 'Live music show'}, {'name': 'Art Expo', 'date': datetime.date(2024, 8, 5), 'description': ''}, and {'name': 'Food Festival', 'date': datetime.date(2024, 9, 10)}. Import datetime to use datetime.date.
Django
Need a hint?

Remember to import datetime and use datetime.date(year, month, day) for dates.

2
Add a variable to count events
Create a variable called event_count and set it to the length of the events list using the len() function.
Django
Need a hint?

Use len(events) to get the number of items in the list.

3
Use template filters for date and default description
Write a Django template snippet that loops over events using {% for event in events %}. Inside the loop, display the event name, the event date formatted as F j, Y using the date filter, and the event description using the default filter with the fallback text 'No description available'. Close the loop with {% endfor %}.
Django
Need a hint?

Use {{ variable|filter }} syntax for filters. The date filter formats dates, and default shows fallback text if the value is empty or missing.

4
Show the total number of events using length filter
Add a line above the loop that displays the total number of events using the length filter on the events list inside double curly braces. The text should read exactly: Total events: X where X is the length of events.
Django
Need a hint?

Use {{ events|length }} to get the number of items in the list inside the template.