top of page

Django - Creating Views

A view is a place where we put our business logic of the application. The view is a python function which is used to perform some business logic and return a response to the user. This response can be the HTML contents of a Web page, or a redirect, or a 404 error.

All the view function are created inside the views.py file of the Django app.


Django View Simple Example

//views.py

import datetime  
# Create your views here.  
from django.http import HttpResponse  
def index(request):  
    now = datetime.datetime.now()  
    html = "<html><body><h3>Now time is %s.</h3></body></html>" % now  
    return HttpResponse(html)    # rendering the template in HttpResponse  

First, we will import DateTime library that provides a method to get current date and time and HttpResponse class.


Next, we define a view function index that takes HTTP request and respond back.

View calls when gets mapped with URL in urls.py. For example

path('index/', views.index),  

Django View Example

// views.py

from django.shortcuts import render  
# Create your views here.  
from django.http import HttpResponse, HttpResponseNotFound  
def index(request):  
    a = 1  
    if a:  
        return HttpResponseNotFound('<h1>Page not found</h1>')  
    else:  
        return HttpResponse('<h1>Page was found</h1>') # rendering the template in HttpResponse  

This method will execute only if the request is an HTTP GET request.

//urls.py

from django.contrib import admin  
from django.urls import path  
from myapp import views  
urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('index/', views.index),  
    path('show/',  views.show),  
]  




Related Posts

See All

Django CRUD (Create, Retrieve, Update, Delete)

Step 1: Create the Django project and app Open your terminal (or command prompt) and run the following commands: # Create the Django project django-admin startproject crud_project cd crud_project # C

Comments


bottom of page