6. Django templates
We can edit the view we just created so that it uses a template. Note we commented out the html created previously and have added the template below it.
def simple_view(request): addresses = Address.object.all() first_address = address[0] resident_name = str(first_address.resident) # html = "Name: "+resident_name+"Address:"+ first_address.street_name+"" return render(request, 'helloworld/simple.html', {'address':first_address, 'name': resident_name})
We’re using a template called simple.html. We haven’t created this yet.
By convention the Django app will keep the templates in a directory called templates – this can be changed in the settings.
We’ve previously created the helloworld subdirectory in templates so we just need to go here and add a file called simple.html.
<!DOCTYPE html> <html> <head></head> <body> <h1>Simple Title For This Page</h1> <p> Name: {{ name }}<br /> Address: {{ address }} </p> </body> </html>
We can use code instead of variable names, eg
Name: {% name.upper() %}
We can also do this:
templates/helloworld/base.html
<!DOCTYPE html> <html> <head> <meta name="keywords" content="HTML,Django,Tutorial"> </head> <body> {% block content %} {% endblock %} </body> </html>
templates/helloworld/simple.py
{% extends 'base.html' %} {% block content %} <h1>Simple Title For This Page</h1> <p> Name: {{ name }}<br /> Address: {{ address }} </p> {% endblock %}
Wednesday 20 October 2021, 693 views
Next post: 7. Django URLs Previous post: 5. Django models
Advanced Web Development index
- 38. Writing API tests
- 37. Testing in Django
- 36. Class-based views in the Django REST framework
- 35. Building a RESTful web service in Django
- 34. Introduction to CRUD, REST and APIs
- 33. Refactoring with generic views in Django
- 32. Django validators
- 31. Django forms (2) – using the ModelForm class
- 30. Django forms (1)
- 29. JavaScript basics
- 28. Adding CSS to the template
- 27. Django templating
- 26. Deleting and updating records
- 25. Joins, filters and chaining commands
- 24. Using the ORM in views.py
- 23. Adding to the database by writing a script
- 22. Adding to the database with Django Admin
- 21. Migrations
- 20. ORM – work through example
- 19. An introduction to the Object-Relational Mapper
- 18. Altering the database
- 17. SQL functions and summaries
- 16. SQL Query performance
- 15. Queries and table joins in SQL
- 14. Inserts and queries in SQL
- 13. Good practice in relational database design
- 12. Limitations to database modelling
- 11. Building a database using SQL
- 10. Introduction to PostgreSQL
- 9. How to start writing a new application in Django
- 8. Building a lightweight project
- 7. Django URLs
- 6. Django templates
- 5. Django models
- 4. Django views
- 3. Creating a new hello app
- 2. Creating a new virtual environment
- 1. Setting up Django
Leave a Reply