Django views

Views in django are like controller in other frameworks. Views help to process the incomming request pull data from database(if required) and then send response to the client. 

Django Views Basics

Django views can be a function or a class. Django view may return plain text or it may returned rendered html. 

For example, a function-based view for rendering simple “hello world” text looks like this. 

from django.http import HttpResponse
def index_view(request):
    return HttpResponse('Hello world!')

This view function will be mapped in URLs like this

from django.urls import path
from .views import  index_view
urlpatterns = [
    path('hello/', index_view, name="demo_index_view"),


A class-based view is similar to a function based view but you need to map in URLs by calling .as_view()  in the file. You will see more about the file in a later chapters. The class-based view are very useful. They have Django has generic view which makes creating, updating, deleting, and listing data from database very easly. Also, in listing database data pagination can be easily applied. The generic views were introduced to ease common database operation with fewer settings. A simple example of listing data with pagination in django class based view looks like this:

from .models import Blog
from django.views.generic import ListView
class BlogList(ListView):
    template_name = "blog/blog_list.html"
    model = Blog
    paginate_by = 10
    context_object_name = 'blog_list'

Here, template_name is the name of HTML file to which this view will render data. You will look at this blog_list.html file in the template tutorial section. The model represents the model that this view needs to pull data from in this case. Blog. You need to pull Blog model from file. The paginate_by variable if set paginates the incoming data, in this case, items are paginated in a group of 10.  The context_object_name represents the variable name that will be used to render in the HTML page defined by template_name. By default if this variable is not set, Django will render the data in object_list variable. The purpose of specifying context_object_name is to let other developers know that this variable is used in the HTML template. It’s a good practice to set this variable. 

Back to creating views for our Portfolio/Blog Project.

Let’s create views for our work in both the blog app and contactus app. 

View for blog app

Go to blog/ > file and add these code in the file. 

from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView, DetailView

from .models import (

# Create your views here.
def index_view(request):
    return HttpResponse('Hellow world!')

def home(request):
    template = 'blog/index.html'
    # show five slider images at max
    slider_images = SliderImages.objects.all()[:5]
    # show six projects
    projects = ProjectCompleted.objects.all()[:6]
    context = {
        'slider_images': slider_images,
        'projects': projects,
    return render(request, template, context)

class AboutPage(ListView):
    template_name = "blog/about.html"
    model = PortfolioAboutPage
    context_object_name = 'about_object'

class BlogList(ListView):
    template_name = "blog/blog_list.html"
    model = Blog
    paginate_by = 10
    context_object_name = 'blog_list'

class BlogDetailView(DetailView):
    template_name = "blog/blog_detail.html"
    model = Blog
    context_object_name = 'blog_object'

Views for contactus app

go to contactus app > and add these code in the file. 

from django.views.generic import CreateView
from django.contrib.messages.views import SuccessMessageMixin
from django.shortcuts import reverse

from .models import Contact

class ContactUs(SuccessMessageMixin, CreateView):
    template_name = 'contactus/contact.html'
    model = Contact
    fields = ['name', 'email', 'suggestion']
    success_message = "your message from %(email)s sent successfully!"

    def get_success_url(self):
        return reverse('contact-us')

Now let’s understand these code. In blog app file you have few functions.

Details for blog app file

1. The index_view(request) function is added to show a simple “hellow world” text rendering. It returns HttpResponse. 

2. The home(request) is used to render the home page. The home page will have slider data and also the project completed data. These data are pulled from the database and passed into the templates in slider_images and projects variable. Function-based views are very helpful when you need to pull data from multiple tables.

3. AboutPage(ListView) : This view is a ListView as it inherits from ListView generic view. It pull data from PortfolioAboutPage model and renders it to the view.

4. BlogList(ListView): Its similar to AboutPage view, it is for our blog.

5. BlogDetailView(DetailView): This view pull single object from database. It tages pk or a slug value in file to identify which object to pull. 

To know more about view and generic views you can read article on official documentation. They have other important generic views as well. 

Details for contactus app file

ContactUs(SuccessMessageMixin, CreateView):This view is a CreateView , which creates object in the database.

In next post, you will see how to setup file for these two view files. 

Leave a Reply

Your email address will not be published. Required fields are marked *