Django Web Framework[Part-5]

Debapriya Basu
4 min readAug 21, 2023

--

In Django the logic which represents the data to the end users is called View.

Source: Django tutorial Meta

View take a web request and return a response. Two types of web requests.

Static Web Request

For a static file with no dynamic content, the HTTP request just needs to map to where the file is located and return that page for rendering. As the static page does not change, nothing else is needed. This is HTTP Request/Response function. In Django we need to create a Python file views.py .

Sample code from my own project

Actions taken under views.py

We can take several action under views.py file.

  1. Process data
  2. Retrieve data
  3. Transform data
  4. Render templates

Routing

Create a view function is not enough, we need to create a URL map to make program understand the flow. Map URL to view function is called Routing. In Django we need to create a file under App folder urls.py(app).

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

urlpatterns = [
path('', views.hello, ),
path('menu/<int:menu_id>', views.menu_by_id, name = 'menu_by_id'),
]

Django creates urls.py file at Project level, but best practice to create urls.py file at App level.

Django always goes first to urls.py of project level. So we need to use include() function for mapping urls.py of project to route to urls.py of app.
urls.py from App | urls.py from Project

What does the view do?

View interacts with both the model and template layers. The primary role of the view function is to fetch the data from the client’s request, apply a certain processing logic to it and send an appropriate response back to the client.

For simplicity, you can say models are equivalent of a database in Django. The view function interacts with the model in either of two ways. It either fetches all or certain objects from the model such as the database table mapped with the model.

Or the request parameters are used to add a new instance of the model thereby inserting a new row in the mapped table.

The client uses the HTTP GET method to provide the data from the model or delete a certain instance. On the other hand, it uses the POST method to indicate that the data in the request is to be used to perform an insert or update operation.

rom django.shortcuts import render     

def myview(request):
if request.method=='GET':
val = request.GET['key']
#perform read or delete operation on the model
if request.method=='POST':
val = request.POST['key']
#perform insert or update operation on the model

Since the web browser is the client of your web application, the response should be in HTML format as a web page, called a web template.

The Django view loads the template web page, inserts certain context data at the placeholders marked with tags, and returns it as the response.

View rendering template

from django.shortcuts import render

def myview(request):

if request.method=='GET':
#perform read or delete operation on the model

if request.method=='POST':
#perform insert or update operation on the model
context={ } #dict containing data to be sent to the client

return render(request, 'mytemplate.html', context)

Class based views

In the above discussion, myview is a regular Python function.

Such views are called function based views. The processing logic in it is very imperative in nature, hence it may be repetitive.

Also, it uses conditional blocks for GET and POST requests. Django offers a more concise alternative in the form of a class-based view.

You create a sub-class of the View class and override its get() and post() methods to separately and cleanly define GET and POST operations.

from django.views import View 
class MyView(View):
def get(self, request):
# logic to process GET request
return HttpResponse('response to GET request')

def post(self, request):
# <logic to process POST request>
return HttpResponse('response to POST request')

Generic views

Django makes the view declaration process still easier with its generic class-based views. The django.views.generic module contains several view classes that provide the functionality required to perform tasks such as rendering a template, showing an instance, showing the list of instances, adding a new model instance, updating an instance and so on.

Some generic views are TemplateView, CreateView, ListView, DetailView, UpdateView to name a few.

You need to subclass the generic view and set the properties like model and template_name. Django will internally perform all the heavy lifting which you had to do by yourself in a function-based view.

What’s Next

Previous topics ⭐️👇

🎯DJango Web Framework[Part-1]

🎯DJango Web Framework[Part-2]

🎯Django Web Framework[Part-3]

🎯Django Web Framework[Part-4]

Next topics ⭐️👇

🎯Django Web Framework[Part-6]

🎯Django Web Framework[Part-7]

I will sum up few more topics which I found interesting to look at. Let’s get learning🍀!

🙏 Thank you for reading to the end! Comment below or email me at dbpr.sinha@gmail.com if you have any questions. For more articles please stay tuned. Also follow my links.

--

--

Debapriya Basu

Engineer @ IKEA group with product mindset and ready to take any challenges.