Part-3
Templates In Django
This chapter will teach you the following:
- Adding html files to your app
- Mapping the urls to your html files and folder.
We Have been writing our html which want to show on the page in return function, but writing the html file,css and javascript in strings is ugly and complex..So let’s make a templates directory where we can store our html files.
It might look like a boilerplate ,well django does have many boiler plates unlike flask ,so to add our html files we’ll have to make a sub directory within our blogapp folder as templates and then another sub directory called blogapp which will will finally hold our html files.This is known as namespacing.So it’s like this..
blog_project/blogapp/templates/blogapp/ ..html files..
Note: If you want to use a template(or html file) in your multiple apps,then you’ll need to put it inside your main project,under the templates foder and add to the DIRS list of TEMPLATES variable in settings.py
blog_project/templates/ ..html files..
Now let’s create html files for home page and the about page.Do this by creating new file in templates/blogapp/directory
templates/blogapp/home.html .. about.html
In the Settings.py file, we have a list with the INSTALLED_APPS name, and our blogapp is missing in the list ,so we need to add our blogapp to the list (so that the templates and other file of the app are found correctly, at least in django 2.x ) with the following code,
INSTALLED_APPS = [
'blogapp.apps.BlogappConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
The first line or item in the list is the path to our blogapp through the blogapp/apps.py file.
Now back to our views file you can now add your edited html files like so..
from django.shortcuts import renderdef home(request):
return render(request,'blogapp/home.html')
def about(request):
return render(request,'blogapp/about.html')
Run Your server and you’ll see the page designed in the html file for respective routes..
Next Up..