0
0
Djangoframework~30 mins

Why templates separate presentation in Django - See It in Action

Choose your learning style9 modes available
Why Templates Separate Presentation in Django
📖 Scenario: You are building a simple website that shows a list of books with their titles and authors. You want to keep the way the data looks separate from the data itself. This helps you change the look later without touching the data or the code that gets the data.
🎯 Goal: Build a Django project that uses templates to separate the data (in views) from the presentation (in templates). You will create a list of books in the view and display them in the template.
📋 What You'll Learn
Create a list of books as dictionaries in the Django view
Create a template to display the list of books
Pass the list of books from the view to the template
Use Django template syntax to loop over the books and show their details
💡 Why This Matters
🌍 Real World
Websites often need to show data like products, articles, or user info. Separating data from design helps teams work together and keeps code clean.
💼 Career
Understanding how to use templates in Django is essential for web developers building maintainable and scalable web applications.
Progress0 / 4 steps
1
Create a list of books in the Django view
In your Django view file, create a variable called books that is a list of dictionaries. Each dictionary should have the keys title and author with these exact entries: {'title': 'The Hobbit', 'author': 'J.R.R. Tolkien'} and {'title': '1984', 'author': 'George Orwell'}.
Django
Need a hint?

Use a list with two dictionaries inside. Each dictionary has keys 'title' and 'author'.

2
Add a context dictionary to pass books to the template
Below the books list, create a variable called context that is a dictionary with the key 'books' and the value books. This will send the books data to the template.
Django
Need a hint?

Use a dictionary with key 'books' and value books.

3
Render the template with the context
At the end of the book_list view, return the result of render(request, 'books.html', context). This will show the template books.html with the books data.
Django
Need a hint?

Use the render function with request, template name, and context.

4
Create the template to display the books list
In the books.html template file, use Django template syntax to loop over books and display each book's title and author inside <li> tags. Use {% for book in books %} and {{ book.title }}, {{ book.author }}. Close the loop with {% endfor %}.
Django
Need a hint?

Use a for loop in the template to show each book's title and author inside a list item.