Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Django – Views

February 13th 2020   1248

What are Django Views?
What are Django Views?

Django Views

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

So in our previous tutorial, 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 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/ 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 tutorial, we have successfully written View in Django. So in the next tutorial, we will see what are Templates in Django.