What are Django Views?

What are Django Views?

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

In this section, we will learn what are Views in Django and how to use views.py to display webpage onto the browser on a web request.

So in our previous section, we have successfully created our UserCreateForm form. Let's see what are Views in Django.

What are the Views?

A View function, or "view" for short, is simply a Python function that is written in views.py file, that takes a web request and returns a web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, etc. So to display a webpage we require two things:

  • A URL associated with the view function

  • A Template (HTML page) which is to be displayed

Write your first view

Let's write the first view. Open the file account/views.py and put the following Python code in it:

from django.shortcuts import render, redirect
from django.views.generic.base import View
from django.contrib.auth import login, authenticate
from . import forms

# Create your views here.

#this is a class based view
class IndexView(View):

    def get(self, request, *args, **kwargs):

        return render(request, "registration/index.html")

#this is a function based view
def signup(request):
    if request.method == 'POST':
        form = forms.UserCreateForm(request.POST)
        if form.is_valid():

            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)

            return redirect('index')
        form = forms.UserCreateForm()
    return render(request, 'registration/signup.html', {'form': form})

That's it! we have written our first view. Next, we need to create a URL mapping for these functions and templates for each view function, so will see them in detail in our next tutorial.

In this section, we have successfully writtenView in Django. So in the next section, we will see what are **Templates** in Django.

Share this