Django Views

  • A view is a place where we put our business logic of the application
  • The view is a python function 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

Types of Views

  • Django views are divided into two major categories:-
    • Function-Based Views
    • Class-Based Views

Function-Based Views

  • It receives HttpRequest object as an argument and returns an HttpResponse Object
# HttpResponse
from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)
# render
from django.shortcuts import render

def home(request):
    context = { 'posts' : Posts.objects.all() }
    return  render(request, 'blog/home.html', context)  

Class Based Views

  • They do not replace function-based views, but have certain differences and advantages when compared to function-based views
from django.views.generic.list import ListView
from .models import Posts
 
class GeeksList(ListView):
 
    model = Posts

Django request

  • Use request instead of HttpRequest

Attributes

HttpRequest.scheme
# http or https

HttpRequest.body
# All details passed from FE

HttpRequest.path
# '/signup/'

HttpRequest.path_info
# '/signup/'

HttpRequest.method
# Type of request (GET, POST etc)

HttpRequest.content_type
# 'text/plain'
# 'application/x-www-form-urlencoded

HttpRequest.GET
# All GET data in Dict form

HttpRequest.POST
# All POST data in Dict form

HttpRequest.META
# A dictionary containing all available HTTP headers.

HttpRequest.headers
# A case insensitive, dict-like object that provides access to all 
# HTTP-prefixed headers (plus Content-Length and Content-Type)
# from the request.
        
HttpRequest.user
# user data

Methods

HttpRequest.get_host()
# '127.0.0.1:8000'

get_current_site(request).domain
# '127.0.0.1:8000'

HttpRequest.get_port()
HttpRequest.is_secure()
HttpRequest.get_signed_cookie('name')

HttpRequest.build_absolute_uri()
# 'http://127.0.0.1:8000/signup/'

HttpRequest.get_full_path()
# '/signup/'

views.py

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

from django.contrib.auth.forms import (UserCreationForm, 
                    AuthenticationForm, PasswordChangeForm)
from django.contrib.auth.decorators import login_required

from django.contrib import messages

from django.contrib.auth import login, authenticate

forms.py

from django.contrib.auth.forms import UserCreationForm
from django.forms import ModelForm

Reference