Homepage View and Template
Explore how to set up the homepage view and template in Django. This lesson guides you through creating the view function, organizing templates, and rendering HTML to display your homepage content. Gain foundational skills to start building functional web pages in Django.
We'll cover the following...
Homepage view
After we create the URL for a specific page, a view for the page also needs to be created.
Add the following code in views.py in the app’s directory to create the view for the Homepage.
The module in line 1 is used to call different helper functions. We use it here to call render (line 4) which helps generate a response that we can render in a template. We’ll talk about the template in the next section.
Homepage template
After we have rendered the request into a template, we need to create a template so that users can see the data being displayed. In Django, these templates are HTML files which display data provided by views.
First, create a folder called templates inside the app’s directory, and then inside the templates folder create a folder with the name of the app (i.e., listings). This helps Django interpreter find the templates for the app without any ambiguity. Create a file named index.html inside of the last folder created. The app’s main folder should look like the image below.
Open index.html and add the following code:
It might be a good idea to get familiar with HTML in order to understand the templates as we go along. For this one, there’s not much going on; just a header and a paragraph. For now, we’ll keep the templates simple like this one. Though later on, we’ll start styling them using Bootstrap.
Let’s try to get the functionality of our website working first, and then we can start making it look pretty. Run the app to see the homepage of our site.
Live demo
Implement the following steps to see the homepage of our Django app:
- You can see listings/views.py opened in the following widget. Copy the code of the Homepage view from the first code snippet and add it to this file.
- Copy the code of the Homepage template from the second code snippet and add it in listings/templates/listings/index.html.
- Click on the Run button to run the app.
"""
ASGI config for example project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'example.settings')
application = get_asgi_application()