Django Django Templates 2 — Questions and Answers
Question 1: Which template tag iterates over a list in Django?
- {% for item in list %} (Correct answer)
- {% each item in list %}
- {% loop item in list %}
- {% iterate item in list %}
Correct answer: {% for item in list %}
The {% for %} tag loops over each item in a sequence and must be closed with {% endfor %}.
Question 2: What does `{{ forloop.counter }}` provide inside a Django for loop?
- The 1-based index of the current loop iteration (Correct answer)
- The total number of items in the loop
- The 0-based index of the current loop iteration
- A boolean indicating the last iteration
Correct answer: The 1-based index of the current loop iteration
forloop.counter gives the current iteration number starting at 1; use forloop.counter0 for a 0-based index.
Question 3: How do you load a custom template tag library in Django?
- {% load mytaglib %} (Correct answer)
- {% import mytaglib %}
- {% include mytaglib %}
- {% use mytaglib %}
Correct answer: {% load mytaglib %}
{% load %} at the top of a template loads a custom tag library from a templatetags directory, making its tags and filters available.
Question 4: What is the `{% csrf_token %}` tag used for in Django forms?
- Inserts a hidden CSRF token field to protect against cross-site request forgery (Correct answer)
- Validates form input on the client side
- Encrypts form data before submission
- Generates a nonce for Content Security Policy
Correct answer: Inserts a hidden CSRF token field to protect against cross-site request forgery
{% csrf_token %} renders a hidden input field with a CSRF token that Django's middleware validates on POST requests to prevent CSRF attacks.
Question 5: Which template filter safely escapes HTML characters in Django?
- escape (Correct answer)
- safe
- sanitize
- html_escape
Correct answer: escape
The escape filter converts characters like <, >, &, and quotes to their HTML entity equivalents to prevent XSS; Django auto-escapes by default.
Question 6: What does marking a variable with `{{ value|safe }}` do in Django templates?
- Disables auto-escaping for that variable, rendering raw HTML (Correct answer)
- Marks the value as safe for database storage
- Validates the value against XSS patterns
- Converts the value to a safe string type
Correct answer: Disables auto-escaping for that variable, rendering raw HTML
The safe filter tells Django's template engine to trust the variable's content and render it as raw HTML without escaping, which should only be used with trusted data.
Which template tag iterates over a list in Django?