0
0
Djangoframework~30 mins

XSS prevention in templates in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
XSS Prevention in Django Templates
📖 Scenario: You are building a simple Django web page that displays user comments. To keep your site safe, you need to prevent Cross-Site Scripting (XSS) attacks by properly handling user input in your templates.
🎯 Goal: Create a Django template that safely displays user comments by preventing XSS attacks using Django's built-in template escaping features.
📋 What You'll Learn
Create a Python dictionary called comments with exact keys and values.
Add a configuration variable safe_comment to mark a comment as safe.
Use Django template syntax to loop over comments and display each comment safely.
Use the safe filter only on the safe_comment variable to allow HTML rendering.
💡 Why This Matters
🌍 Real World
Web developers must prevent XSS attacks to protect users from malicious scripts embedded in user-generated content.
💼 Career
Understanding template escaping and safe rendering is essential for secure web application development in Django.
Progress0 / 4 steps
1
Create the comments dictionary
Create a Python dictionary called comments with these exact entries: "user1": "Hello, world!", "user2": "", and "user3": "Welcome to Django!".
Django
Need a hint?

Use curly braces to create a dictionary and include the exact keys and values as strings.

2
Add a safe comment variable
Add a variable called safe_comment and set it to the value of comments["user3"].
Django
Need a hint?

Assign the value of the key "user3" from the comments dictionary to safe_comment.

3
Write the Django template loop
Write a Django template loop using {% for user, comment in comments.items %} to iterate over comments and display each comment inside a <p> tag. Use the default escaping to prevent XSS.
Django
Need a hint?

Use Django template tags {% for %} and {% endfor %} with {{ comment }} inside a paragraph tag.

4
Render the safe comment with the safe filter
Add a line in the Django template to display the safe_comment variable inside a <p> tag using the safe filter: {{ safe_comment|safe }}.
Django
Need a hint?

Use the safe filter to allow HTML in safe_comment but keep escaping for others.