In Django, templates are used to separate the presentation layer from the business logic. What is the main benefit of this separation?
Think about who works on design and who works on code in a team.
Separating templates from logic lets designers focus on HTML and CSS, while developers handle Python code. This clear division improves teamwork and maintainability.
Consider a Django template that contains complex data processing logic instead of just displaying data. What is the likely outcome?
Think about code clarity and who should handle logic.
Templates are meant for presentation. Complex logic in templates makes them messy and hard to maintain. Logic should stay in views or models.
Which of the following Django view snippets correctly passes a list of items to a template named 'list.html'?
def item_list(request): items = ['apple', 'banana', 'cherry'] # Fill in the correct return statement below
Check the order of arguments in the render function.
The render function takes the request, template name, then context dictionary. Only option A follows this order correctly.
Given the context {'user': {'name': 'Anna', 'age': 30}}, what will this Django template output?
{% if user.age > 18 %}
<p>Welcome, {{ user.name }}!</p>
{% else %}
<p>Access denied.</p>
{% endif %}Check the age condition and how variables are displayed.
The user's age is 30, which is greater than 18, so the first block runs and shows the welcome message with the user's name.
Consider this Django template snippet:
{% for item in items %}
{{ item.name }}
{% endfor %}The view passes {'items': ['apple', 'banana']} as context. Why does this cause an error?
Think about the type of each item in the list and what the template tries to access.
The context 'items' is a list of strings. Strings do not have a 'name' attribute, so {{ item.name }} causes an error.