0
0
Djangoframework~30 mins

Custom template filters in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Creating Custom Template Filters in Django
📖 Scenario: You are building a Django web app that shows a list of product prices. You want to display prices formatted as currency with a dollar sign and two decimals.
🎯 Goal: Create a custom Django template filter called currency that formats a number as US dollars (e.g., 12.5 becomes "$12.50") and use it in a template to display product prices.
📋 What You'll Learn
Create a Python dictionary called products with these entries: 'apple': 0.5, 'banana': 0.3, 'cherry': 1.2
Create a variable called currency_symbol and set it to '$'
Write a custom template filter function called currency that takes a number and returns a string formatted as currency_symbol plus the number with two decimals
Use the currency filter in a Django template to display each product's price formatted as currency
💡 Why This Matters
🌍 Real World
Custom template filters help format data in Django templates to improve user experience, such as showing prices in a readable currency format.
💼 Career
Knowing how to create and use custom template filters is important for Django developers to customize how data is displayed in web applications.
Progress0 / 4 steps
1
Set up the product prices dictionary
Create a Python dictionary called products with these exact entries: 'apple': 0.5, 'banana': 0.3, and 'cherry': 1.2.
Django
Need a hint?

Use curly braces {} to create a dictionary with keys and values separated by colons.

2
Add a currency symbol variable
Create a variable called currency_symbol and set it to the string '$'.
Django
Need a hint?

Assign the string '$' to the variable currency_symbol.

3
Write the custom template filter function
Write a function called currency that takes one argument value. It should return a string combining currency_symbol and value formatted with two decimal places (e.g., "$12.50").
Django
Need a hint?

Use an f-string to format the number with two decimals and add the currency symbol in front.

4
Use the custom filter in a Django template
In a Django template, use a for loop with variables product and price to iterate over products.items(). Inside the loop, display the product name and the price using the currency filter like this: {{ price|currency }}.
Django
Need a hint?

Use Django template syntax with {% for %} and {{ }} to loop and display filtered prices.