Django Tutorial
About Lesson

In this Django Tutorial we are going to learn about Django Templates, in this lesson we want to learn that how you can render a template in django, also how you can send data from your view functions to the html templates, so for rendering templates in django we can use render() function. it combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text. you can pass different arguments in the render() function, some of them are required and some them are optional.



So this is the syntax.



Required arguments

  • request: The request object used to generate this response.
  • template_name: The full name of a template to use or sequence of template names. If a sequence is given, the first template that exists will be used.


Optional Arguments

  • context: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template.
  • content_type: The MIME type to use for the resulting document. Defaults to 'text/html'
  • status: The status code for the response. Defaults to 200




OK now first of all you need to create templates folder, so there are two ways that you can add your templates folder, the first way is that you can add this folder in your specific app, the second way is that you can add this folder in the project directory, for example in here i want to add my templates folder in the mysite directory.



I have created my templates folder, after that i have added an index.html file in my this folder.

Django Tutorial - Django Templates
Django Tutorial – Django Templates




This is a simple index.html.




Now we want to render this template, so open your from your polls app, and add this code.




Also open because we need to notify django about this templates folder that is located in our project directory. so in the DIRS sections you can write templates like this.





Now go to http://localhost:8000/, this will be the result.

Django Templates
Django Templates





OK now some times you need to send some data from your view function to the html files, for example you have retrieved your data from the database and you want to show them to the users in your html files, so for this we can use templates context in django. let’s bring changes to our Index view function in file. you can see that we are sending some data from our views functions to the html file using context.





In your index.html file, you can get these data using template variable {{}}, and you need to add the key of the dictionary for accessing the data.





If you check your website we have the data.

Django Template Context
Django Template Context


Thank you for visiting my website! If you enjoyed the free courses, please consider supporting my works on Patreon.
Exercise Files
No Attachment Found
No Attachment Found