top of page

Django Part III - Views

Updated: Feb 16, 2022


What is Views ?


The view component of the model view controller (MVC) architecture is responsible for presenting data to users for consumption and viewing. The View is the python function which takes a request from the web and returns a web response. Response can be simple http response, an HTML template response or HTTP redirect response that redirects to another page.


In this blog we will show you how to use views in django as a data display and view tool. There are two types of view class based views and function based views. If you don't know about django you can check out this blog click here or if you want to learn how to build a simple blog web application using django.


Sample


After you are creating complete project of django, we can create create view in my_blog_site/views.py


In the following code we import the Http response from the django http module. after that we define a function sample_view. This is the view function. All the view function take a HTTP request as a first parameter. The typically name of that is request. The view return is a Http response which is create the response.


Code :


# import Http Response from django
from django.http import HttpResponse
# create a function
def sample_view(request):
	# convert to string
	html = "Welcome to the Codersarts"
	# return response
	return HttpResponse(html)

Lets get this view to working in my_blog_site/urls.py


code

from django.contrib import admin
from django.urls import path
from .views import sample_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', sample_view),
]



There are two type of view

  • Function based views

  • class based views

Function based view


In function based view developer used a function in python which receives as a argument http request object and return the http response object. Generally function based view are divided into four stratergies create, retrieve, update and delete.


Example


code :

def my_view(request, pk):
  template_name = 'post_form.html'
  form_class = Mypost

  form = form_class

  if request.method == 'POST':
    form = form_class(request.POST)
    if form.is_valid():
      form.save()
      return HttpResponseRedirect(reverse('list-view'))

  return render(request, template_name, {'form': form})

Class based view


This view allows creating a view from the inherited class. class based views is the alternative way of view implementation as python object instead of function. in class based view can be extend more functionalities using mixins. because of code reuseability, we do not need to write same again, it help to reduce the code duplication.


Code :



class MyView(View):
  template_name = 'post_form.html'
  form_class = MyForm

  def get(self, request, *args, **kwargs):
    form = self.form_class
    return render(request, template_name, {'form': form})

  def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)
    if form.is_valid():
      form.save()
      return HttpResonseRedirect(reverse('list-view'))
    else:
      return render(request, self.template_name, {'form': form})

List view


As the name says, it will create the list of items in the project from the database. Here is the simple list view of items


Code :


from django.views.generic import ListView

from . models import Sample

class ItemListView(ListView):

model = Sample

# a html file that will display a list of all the items in inventory model

template_name = '/items.html'

context_object_name = 'items' # how the list will be referred to in the html template


Details view


This view is used to display the data for only one record from the database. Here is the code of sample to print the single record from the database


Code :


from django.views.generic import DetailView

from . models import Sample


class ItemDetailView(DetailView):

model = Sample

template_name =/detail.html'

context_object_name = 'item'


How Codersarts can Help you in Django ?


Codersarts provide:

  • Django Assignment help

  • Django Error Resolving Help

  • Mentorship in Django from Experts

  • Dajngo Development Project

If you are looking for any kind of Help in Django Contact us


bottom of page