Creating views in Django
Building web applications with Python & Django
🕑 This lesson will take about 15 minutes
What is a view?
In Django, a view is a Python function or class that handles web requests and returns web responses to users. Views are an important part of Django’s Model-View-Template (MVT) architecture, and the primary role of views is to process HTTP requests, interact with models, and render templates to generate responses or content that can be sent back to the user.
Most web development frameworks (such as Django) follow the same idea:
we create functions that our application can call (views)
we tell our application when to call these functions based on user actions (using routing)
we tell the application what we want it to display to the user (using templates)
In one of the earlier lessons, we already created a basic view for the home page that is responsible for displaying “Hello, world!” to the user when they request the home page of the web application. However, we can create more complex views that might grab data from the database, process data, and then use a template to display dynamic content to the user.
Creating views
Open the views.py file in your app folder (eg. in the myapp folder). Modify the file so it has the following code. In our code, we will have two different function-based views - one for the ‘home’ page (index) and one for the ‘about’ page. Each view will take a request from the user, return the request data and use a template (a file containing HTML code) to render content to display back to the user. For now, each HTML file will contain static content but later on we will look at how to make it dynamic (eg. display different content on each page depending on what the user has requested or what data is in the database). After editing the code, make sure to save it.
Creating templates
Inside your app folder (eg. myapp), create a new folder called templates. Inside this templates folder, create two new files - one called index.html and one called about.html (both are HyperText Markup Language / HTML files).
Add your own HTML code to the index.html file or use the example code below to get started. If you’re not familiar with HTML & CSS code, you might want to follow the free web design course here.
Add your own HTML code to the about.html file or use the example code below to get started.
For now, these two pages only have static HTML code but later we will make the application more dynamic! The next step is to now implement routes so our application knows when to return these two pages to the user (eg. when the user requests the home page then display the home page, and when the user requests the about page the display the about page). That will be the focus of the next lesson!
Next lesson: Implementing routes in Django