Views
Getting our models done is good and all but our site is still not finished, we still need a way to let other users signup on our site, create posts, etc. for these we need to create views.
Views can be functions(FBV) or classes(CBV) that receive HTTP requests (POST, GET, DELETE, etc.) from the browser (or other user-agents) and return an HTTP response in the form of an HTML template, JSON string, plain text or other forms of responses as defined by the developer.
Let's go right ahead to create our first view that'll be mapped to the home route of our site, this will just be a regular python function with request
as a parameter and a return statement.
1# ./crud_app/views.py
2from django.shortcuts import render
3from django.http import HttpResponse
4
5def home(request):
6return HttpResponse("This is the home page")
Next, we need to tell Django which route to map to this view function, to do this, we need to head over to the urls.py
file and add a path pointing to the function like so:
1# ./crud_app/urls.py
2from django.urls import path
3from crud_app import views
4
5urlpatterns = [
6 path('', views.home, name='home'),
7]
In the above code block, we have imported views from our crud_app and mapped the home function to the root path with the path function. (The path function, takes the route as the first argument, the view function or class as the second argument, and a name as the third argument.).
Finally, we need to include our app's urls.py
file in the main urls.py
file like so:
1# ./django_crud/urls.py
2from django.contrib import admin
3from django.urls import path, include
4
5urlpatterns = [
6 path('admin/', admin.site.urls),
7 path('', include('crud_app.urls')), # <--- Added this line
8]
now running our server and opening http://127.0.0.1:8000/
in our browser should result in the following.

Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.