Prerequisites:
Before practicing the examples of this tutorial, you have to complete the following tasks:
- Install the Django version 3+ on Ubuntu 20+ (preferably)
- Create a Django project
- Run the Django server to check whether the server is working properly or not
Setup a Django App:
A. To create a Django app named viewapp, run the following command:
B. To create the user for accessing the Django database, run the following command. If you have created the user before then skip this part:
C. Add the app name in the INSTALLED_APP part of the settings.py file.
…..
'viewapp'
]
D. Create a folder named templates inside the viewapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file.
{
….
'DIRS': ['/home/fahmida/django_pro/viewapp/templates'],
….
},
]
Create a Simple function-based View:
Open the views.py file from the viewapp folder and replace the content of this file with the following script. index() function is used in the script to create the HTML content that will be sent to the browser using the HttpResponse() method. Here, the current date and time of the system will be read using the today() function and the current date value will be generated before sending to the browser.
Views.py
from datetime import date
# Import the HttpResponse module to send data from view to template
from django.http import HttpResponse
# Define function to create function-based view
def index(request):
# Read the current date
today = date.today()
# Set static data for the view
content = "<center><h1 style='color:green'>Welcome to LinuxHint</h1><h2>"
content += "Today is " + today.strftime("%B") + " " + today.strftime("%d") + ", " + str(today.year) + "</h2></center>"
# Sent the content to the browser
return HttpResponse(content)
Modify the content of the urls.py file with the following script. In the script, the ‘welcome/’ path is defined to call the index() function that will send the HTML content to the template file.
urls.py
from django.urls import path
# Import view module
from viewapp import views
# Call index method to display the content
urlpatterns = [
# Define path to call index() function
path('welcome/', views.index)
]
Run the following URL from the browser that will show the following output. A formatted headline text and the current date value are shown in the output.
http://localhost:8000/welcome/
Create a Simple class-based View:
Create a views2.py file inside the viewapp folder and add the following script. MyView class is defined in the script that contains a method named get(). A list variable named listdata is declared in the script to create a list of 10 random numbers. The values of the list will be passed to the template through the HttpResponse() method when this view is called. the random module has been used in the script to generate a random integer number in each iteration of the for loop using the randint() function.
views2.py
from django.http import HttpResponse
# Import view module
from django.views import View
# Import random module
import random
# Define class for class-based views
class MyView(View):
def get(self, request):
# Declare the list variable
listdata = []
# Add the first element of the list
listdata.append('<center><h2>he list of 10 random numbers are:</h2>')
# Iterate the loop for 10 times
for n in range(10):
# Generate a random number within 1 to 50
random_number = random.randint(1, 50)
# Add the random number in the list
listdata.append(random_number)
# Add a break element in the list
listdata.append('<br/>')
# Add the last element of the list
listdata.append('</center>')
# Send the list values to the browser
return HttpResponse(listdata)
Modify the content of the urls.py file with the following script. In the script, the “number/” path is defined to call the MyView.as_view() method that will send the data of the list to the template file.
urls.py
from django.urls import path
# Import view module
from viewapp import views
# Import MyView class
from viewapp.views2 import MyView
# Call the get method of MyView class
urlpatterns = [
# Define path to call index() function
path('welcome/', views.index),
# Define path to call MyView.as_view() method
path('number/', MyView.as_view()),
]
Run the following URL from the browser that will show the following output. The numbers of the output will be changed if the page is refreshed because each number of the list will be generated randomly.
Conclusion:
The output of the web application depends on the script of the view file that is a major part of any web application. Function-based views are mostly used in the early version of the Django app and now class-based vies are used in most applications of Django. The ways of creating both types of views have been shown in this tutorial to help the new Django users create their views based on their application.