0% found this document useful (0 votes)
4 views

2 -Django View

Django Views are essential components of the MVT structure, acting as the user interface that processes web requests and returns responses. They can be implemented as Function Based Views or Class Based Views, with examples provided for both types, including how to create and render views using models. The document also outlines the steps for setting up views in Django, including URL routing and template creation.

Uploaded by

Sami Jee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

2 -Django View

Django Views are essential components of the MVT structure, acting as the user interface that processes web requests and returns responses. They can be implemented as Function Based Views or Class Based Views, with examples provided for both types, including how to create and render views using models. The document also outlines the steps for setting up views in Django, including URL routing and template creation.

Uploaded by

Sami Jee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Django View

1
Django View

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.
2
3
Django View Example
Illustration of How to create and use a Django view using an
Example. Consider a project named gktcs_lms having an app named
lms.
After you have a project ready, we can create a view in lms/views.py

# import Http Response from django


from django.http import HttpResponse
# get datetime
import datetime

# create a function
def geeks_view(request):
# fetch date and time
now = datetime.datetime.now()
# convert to string
html = "Time is {}".format(now)
# return response
return HttpResponse(html) 4
Django View Example

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 geeks_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.

5
Django View Example

Let’s get this view to working, in lms/urls.py

from django.urls import path

# importing views from views.py


from .views import geeks_view

urlpatterns = [
path('', geeks_view),
]

6
Now, visit http://127.0.0.1:8000/

7
Types of Views
Django views are divided into two major categories :-

❑ Function Based Views


❑ Class Based Views

8
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.

9
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 lms/models.py

from django.shortcuts import render


# relative import of forms
from .models import GeeksModel

def list_view(request):
# dictionary for initial data with
# field names as keys
context ={}
# add the dictionary during initialization
context["dataset"] = GeeksModel.objects.all()
return render(request, "list_view.html", context)

10
Function based view Example

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

11
Function based view Example

Enter following commands

12
Function based view Example

Now we have everything ready for back end. Verify that


instances have been created from
http://localhost:8000/admin/lms/gktcsmodel/

13
Function based view Example
Let’s create a view and template for the same. In lms/views.py

from django.shortcuts import render

# relative import of forms


from .models import *

def list_view(request):
# dictionary for initial data with
# field names as keys
context ={}
# add the dictionary during initialization
context["dataset"] = GktcsModel.objects.all()

return render(request, "list_view.html", context)


14
Function based view Example
Create a template in templates/list_view.html

<div class="main">

{% for data in dataset %}.

{{ data.title }}<br/>
{{ data.description }}<br/>
<hr/>

{% endfor %}

</div>

15
Function based view Example

Let’s check what is there on http://localhost:8000/

16
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.

17
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.

18
Class based view Example
In lms/views.py

from django.views.generic.list import ListView


from .models import *

class GktcsList(ListView):

# specify the model for list view


model = GktcsModel

19
Class based view Example

Now create a url path to map the view. In lms/urls.py

from django.urls import path, include


from .views import *

urlpatterns = [
path('', GktcsList.as_view()),
]

20
Class based view Example
Create a template in templates/lms/gktcsmodel_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>
21
Class based view Example
Let’s check what is there on http://localhost:8000/

22

You might also like