Creating views in Django

Django View is an important part of the Django structure.

In this tutorial, you’ll learn how to create Django views and render them.

I. What is a view in Django?

A view is anything that a web browser can display. For example, it can be HTML content of a web page, a redirect, a 404 error, or an image.

II. Types of Views

There are two major Django views.

I’ve written separate posts about them, so you can check them for more info.

III. Create a view in Django

First, we navigate to appName -> views.py. This views.py file will store different views for our application.

To create our first view, we’ll write a function that takes in a request.

In this example, we’ll simply return an HttpResponse (A very simple response that includes a response code of 200 and a string of text that can be displayed in a web browser) of “My blog”.

To do this, we include django.http import HttpResponse.

Our file now looks like:

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
    return HttpResponse('<h1>My blog</h1>')

To associate the view we have just created with a specific URL; we create another file called urls.py in our app.

We already have a urls.py file for the whole project, but we should have a separate one for each individual app.

Navigate to appName -> urls.py and create a list of URL patterns that a user might visit while using our website.

  1. We have to import:
  • from django.urls import path (reroute URLs)
  • from . import views (import any functions we’ve created in views.py.)
  1. Create a list called urlpatterns.

  2. For each URL, add an item to the urlpatterns list that contains a call to the path function with two or three arguments:

  • A string representing the URL path
  • a function from views.py to call when that URL is visited
  • a name for that path (optionally) in the format name="something".

For example

from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index")
]

We’ll then need to point the root URLconf at blog.urls module.

  • Navigate to projectName -> urls.py
  • Import include function from django.urls in the header.
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include("blog.urls")),
]

Now run:

python manage.py runserver

We’ll see the text “My blog” in http://localhost:8000/blog/.

V. Add another page in Django application

If we’d like to add another page in Blog app, we need to:

  • Add function in views.py
  • Add path in app’s urls.py

For example, if we’d like to create an About page in Blog app.

  1. Navigate appName -> views.py and add
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
    return HttpResponse('<h1>My blog</h1>')

def about(request):
    return HttpResponse('<h1>About</h1>')
  1. Navigate appName -> urls.py and add
from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("about/", views.about, name="blog-about")
]

VI. Optional

If we have different users, we can implement individual URL paths for each user.

For example, in views.py, we have the function greet.

def greet(request, name):
    return HttpResponse(f"Hello, {name.capitalize()}!")

In urlpatterns of urls.py, we add:

path("<str:name>", views.greet, name="greet")

We’re no longer looking for a specific word or name in the URL, but any string that a user might enter.

For instance, if user type localhost:8000/blog/hanna, it will return Hello, Hanna

VII. Summary

Here are 2 steps to create a view.

  1. Create an index function in views.py
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, "blog/index.html")
  1. Create urls.py file within our new app’s directory, and update it
from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index"),
]