Theoretical Paper
- Computer Organization
- Data Structure
- Digital Electronics
- Object Oriented Programming
- Discrete Mathematics
- Graph Theory
- Operating Systems
- Software Engineering
- Computer Graphics
- Database Management System
- Operation Research
- Computer Networking
- Image Processing
- Internet Technologies
- Micro Processor
- E-Commerce & ERP
Practical Paper
Industrial Training
Views In Django | Python
Django Views are one of the vital participants of MVT Structure of Django. A View is the user interface — what you see in your browser when you render a website. It is represented by HTML/CSS/Javascript and Jinja files. As per Django Documentation, A view function 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, or an XML document, or an image, anything that a web browser can display.
Illustration of How to create and use a Django view using an Example. Consider a project named mcatutorialshaving an app namedmcatutorials.
Refer to the following articles to check how to create a project and an app in Django.
After you have a project ready, we can create a view in mcatutorials/views.py,
# import Http Response from django from django.http import HttpResponse # get datetime import datetime # create a function def mcatutorials_view(request): # fetch date and time now = datetime.datetime.now() # convert to string html = "Time is {}".format(now) # return response return HttpResponse(html)
Let’s step through this code one line at a time:
- First, we import the class HttpResponse from the django.http module, along with Python’s datetime library.
- Next, we define a function called mcatutorials_view. This is the view function. Each view function takes an HttpRequest object as its first parameter, which is typically named request.
- The view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object.
For more info on HttpRequest and HttpResponse visit – Django Request and Response cycle – HttpRequest and HttpResponse Objects
Let’s get this view to working, in mcatutorials/urls.py,
from django.urls import path # importing views from views..py from .views import mcatutorials_view urlpatterns = [ path('', mcatutorials_view), ]
Now, visit http://127.0.0.1:8000/,
To check how to make a basic project using MVT (Model, View, Template) structure of Django, visit Creating a Project Django.
Types of Views
Django views are divided into two major categories :-
- Function Based Views
- Class Based Views
Function Based Views
Function based views are writter using a function in python which recieves as an argument HttpRequest object and returns an HttpResponse Object. Function based views are generally divided into 4 basic strategies, i.e., CRUD (Create, Retrieve, Update, Delete). CRUD is the base of any framework one is using for development.
Function based view Example –Let’s Create a function based view list view to display instances of a model. let’s create a model of which we will be creating instances through our view. In mcatutorials/models.py,
# import the standard Django Model # from built-in library from django.db import models # declare a new model with a name "McatutorialsModel" class McatutorialsModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title
After creating this model, we need to run two commands in order to create Database for the same.
Python manage.py makemigrations Python manage.py migrate
Now let’s create some instances of this model using shell, run form bash,
Python manage.py shell
Enter following commands
>>> from mcatutorials.models import McatutorialsModel >>> McatutorialsModel.objects.create( title="title1", description="description1").save() >>> McatutorialsModel.objects.create( title="title2", description="description2").save() >>> McatutorialsModel.objects.create( title="title2", description="description2").save()
Now if you want to see your model and its data in the admin panel, then you need to register your model.
Let’s register this model. In Mcatutorials/admin.py,
from django.contrib import admin from .models import McatutorialsModel # Register your models here. admin.site.register(McatutorialsModel)
Now we have everything ready for back end. Verify that instnaces have been created from http://localhost:8000/admin/mcatutorials/mcatutorialsmodel/
Let’s create a view and template for the same. In mcatutorials/views.py,
from django.shortcuts import render # relative import of forms from .models import McatutorialsModel def list_view(request): # dictionary for initial data with # field names as keys context ={} # add the dictionary during initialization context["dataset"] = McatutorialsModel.objects.all() return render(request, "list_view.html", context)
Create a template in templates/list_view.html,
< div class="main"> {% for data in dataset %}. {{ data.title }}< br/> {{ data.description }}< br/> < hr/> {% endfor %} < /div>
Let’s check what is there on http://localhost:8000/
Similarly, function based views can be implemented with logics for create, update, retrieve and delete views.
Django CRUD (Create, Retrieve, Update, Delete) Function Based Views :-Create View – Function based Views Django
Detail View – Function based Views Django
Update View – Function based Views Django
Delete View – Function based Views Django
Class Based Views
Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:
- Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching.
- Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components.
Class-based views are simpler and efficient to manage than function-based views. A function-based view with tons of lines of code can be converted into a class-based views with few lines only. This is where Object-Oriented Programming comes into impact.
Class based view Example – In mcatutorials/views.py,
from django.views.generic.list import ListView from .models import McatutorialsModel class McatutorialsList(ListView): # specify the model for list view model = McatutorialsModel
Now create a URL path to map the view. In mcatutorials/urls.py,
from django.urls import path # importing views from views..py from .views import McatutorialsList urlpatterns = [ path('', McatutorialsList.as_view()), ]
Create a template in templates/mcatutorials/mcatutorialsmodel_list.html,
< ul> < !-- Iterate over object_list --> {% for object in object_list %} < !-- Display Objects --> < li>{{ object.title }}< /li> < li>{{ object.description }}< /li> < hr/> < !-- If objet_list is empty --> {% empty %} < li>No objects yet.< /li> {% endfor %} < /ul>
Let’s check what is there on http://localhost:8000/
Django CRUD (Create, Retrieve, Update, Delete) Class Based Generic Views :-
- CreateView – Class based Views Django
- DetailView – Class based Views Django
- UpdateView – Class based Views Django
- DeleteView – Class based Views Django
- FormView – Class Based Views Django