Django Views – 6 Simple Steps to Create View Component for Django Project

In this tutorial, we will learn about the view component of Django in detail, discuss the difference between class-based views and function-based views and the process of creating views in Django. Before starting this tutorial, we recommend you to complete Django models tutorial as we will be learning how to access the data of models in view.

Django as an MVC architecture follows one design philosophy, loosely coupled. By loosely coupled we mean that modifying an individual component should have a small to no effect on other components.

Django Views

We will first discuss the view component of the MVC.

Django Views Component

1. Views in MVC Architecture

View is a component in Django MVC architecture that contains the logic which is to be displayed to the user. In a traditional MVC architecture, it implements that by coordinating with both model and controller. It poses a problem that the views depends on both model and controller so it renders by two components. This violates the design philosophy of MVC since one component is dependent on other components too much.

Website design changes much often than the business logic and view most of the times contain both of them thus coordinating with both the controller and model. This makes it difficult for front-end and back-end developers to coordinate their data with components for displaying.

2. Views in MTV Architecture

The above-mentioned problems were solved by Django’s MTV architecture where the view was only containing the business logic, i.e., which webpage to be rendered at what input and also became a mediator between the model and template.

One of the important questions that arise from here – Is view the controller in Django?

The answer is ‘no’ because Django Views are only corresponding to the particular template, they are technically not selecting a model or view by themselves.

This question arises because it is the work of the controller in MVC to select the view for the particular data.

Now, the question that would be arising in your mind – Which component is the controller?

Actually, it’s the Django Framework itself and therefore, it’s the best framework because the controller is the most complex part of the code as it has to control and communicate with every component, efficiently. Therefore, it needs to be written precisely and that is solved by the Django Framework.

Now, we will discuss the difference between the views supported by Django; Class- based Views and Function-based Views.

Class-Based Views vs Function-Based Views

Class-Based Views

Django firstly started with only Function-Based Views, but then added Class-Based Views as a way to templatize functionality. Therefore, we didn’t have to write boilerplate (i.e. the same code) code over and over again. CBVs is a way to increase productivity and create it so that we don’t have to write much code.

Organization of code in relation to specific HTTP methods (GET, POST, etc.) displays as separate methods instead of conditional branching.

Object directed techniques like mixins (multiple inheritances) factors code into reusable components.
The Class-Based Views don’t take place of Function-Based Views but thanks to the inheritance they are easy in implementing and are more optimal.

Function-Based Views

A View function, or view for short, is a Python function that takes a Web request and gives a Web response. This response is the HTML contents of a Web page, or an XML document, or a redirect, or a 404 error, or an image. The View itself consists of whatever arbitrary logic requires to return that response.

This function is easy in implementing and it’s quite useful but the main drawback is that on a large size Django project, there are generally many similar functions in the views. One instance is that all objects of a Django project have CRUD operations, therefore this code repeats unnecessarily. This was the main reason for the creation of Generic Class-based views.

Creating Django Views in Easy Steps

In the previous tutorial we generated a model now we will be connecting our model with the view. We have actually used view.py in our Django App tutorial but here we will perform it again from the beginning.

Here are the steps to create Django views for our project:

Step 1. In our student app directory create a new python file named urls.py.

Step 2. Inside that file copy this code as it is.

from django.urls import path
from . import views
urlpatterns = [
path('', views.student_show, name = 'student_show'),
]

 

Django Views - student show command

Understanding the code:

Here, we are creating a urls file for our application rather than the whole project. This urls file will contain all the URLs inside it related to our app. Thus, we get a cleaner main urls_config file.

Now, we will be connecting our project with the application.

Step 3. Open the urls.py file of the project that is in the root folder.

Step 4. Now add this item in the urlpatterns list.

path(‘student/’, include(‘student.urls’)),

 

Django Views - student urls command

Understanding the Code:

This code is actually directing our main urls file to locate and run urls file in the student directory when the URL contains the ending as student/.

Explore Unique Django Features in detail

Step 5. Now in the student directory, open the views.py file

from django.shortcuts import render
from django.http import HttpResponse
def student_show(request):
    x = []
    for i in range(10):
        x.append(i)
    return HttpResponse("<h1>DataFlair Django Tutorials</h1>The Digits are {0}".format(x))

 

Django Views - views.py file

Understanding the Code:

Here we have imported HttpResponse from the library django.http because we need to respond in the HTTP format. Also, we are passing the parameter request to the function.

Every view function will have their first parameter as request.

After that, we wrote a simple python program of storing digits 0-9 in a list and we passed on that list as a string to the HttpResponse. It will then covert the same as HTTP and that will be returned to our browser as HTML which then renders it that way.

This Views file is special as you can see, we are passing HTML as a string and that presents on the browser.

Step 6. To run this view simply type in the url bar, http://localhost:8000/student/

Make sure to run the Django server. Now, you can imagine, with that level of integration of python with the web, you can easily play with your data in Django.

The output of the above view should be:

Django Views - Output of View

Check out Top Django Books for enhancing Django Development knowledge

If you will check the HTML in the browser then you will only see what passes as the HttpResponse in the String and not any python code.

That’s how we can generate Views in Django. This was the simplest form of View, you can actually do a lot more than writing the HTML code in the string.

But still, this process of web development keeps the rendering output in the server file rather than on the resource server. For that, Django’s 3rd component Templates is there.

Summary

Django is different from other frameworks as that there is a certain way to perform tasks in Django, The Django Way and we are learning the same in our Django Tutorials. Although sometimes Django is criticized for its monolithic behavior but it is rather pleasant because there is a very logical way to perform activities.

In this tutorial, we covered the concept of Django views and how we can connect and generate views in Django.

So, now you must be cleared with the concept of Django Views. If you have any queries related to the topic, don’t hesitate to enter in the comment section. We will surely resolve it as soon as possible.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.