Django Views
Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page. (Note that if you’ve used other frameworks based on the MVC (Model-View-Controller), do not get confused between Django views and views in the MVC paradigm. Django views roughly correspond to controllers in MVC, and Django templates to views in MVC.)
Illustration of How to create and use a Django view using an Example. Consider a project named w3wiki having an app named geeks.
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 geeks/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)
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.
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 geeks/urls.py,
from django.urls import path
# importing views from views..py
from .views import geeks_view
urlpatterns = [
path('', geeks_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.
Views In Django | Python
Django Views are one of the vital participants of the MVT Structure of Django. 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, a redirect, a 404 error, an XML document, an image, or anything that a web browser can display.
Contact Us