top of page

Views In Django | Python

Django View Example

How to create and use a Django view using an Example. Consider a project named codewithpankaj having an app named p4n-app.


After you have a project ready, we can create a view in p4n-app/views.py,


# import Http Response from django
from django.http import HttpResponse
# get datetime
import datetime

# create a function
def p4n_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.

Let’s get this view to working, in p4n-app/urls.py,

from django.urls import path

# importing views from views..py
from .views import p4n_view

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



Related Posts

See All

Commenti


bottom of page