Updated May 4, 2023
Introduction to Django Views
All views for a Django application are placed in the views.py file. Here a view is a Python function that takes in a request and returns a response. The response can be an HTML-oriented web page, or it could be an XML document, even an error message, or even an image. The view itself holds that anything subjective in logic is essential to return as a response. The code can be placed anywhere needed until it is associated with the Python path. Every view is callable and can take a request and response. It is more than a function.
How to Create a Plain Django View?
Below we learn how to create a plain Django View:
1. Declare the Function in the views.py file of the Django Application
For Declaring the view in Django, we need an HTTP request and a response. The Django framework automatically creates the HTTP request, while the programmer is responsible for generating the response for this request. The programmer will create this response using the HttpResponse() method from the Django.http package. HttpResponse has subclasses counting Streaming HttpResponse, JsonResponse, and FileResponse.
Each function created in the views.py file is considered a separate view for that application.
Code:
from Django.shortcuts import render
from Django.http import HttpResponse
def view1(request):
return HttpResponse ("Hello World")
2. Tag the view in urls.py File
This is the process of creating a url for the view. The mentioned URL will serve as the access point to reach the specified web page.
- Import the library from django.conf.urls import url.
- Declare a url entry in the urlpatterns list
url(url_path , view_to_be_tagged , name_for_this_view)
Code:
from django.contrib import admin
from django.conf.urls import url
from Django_app1 import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'admin/', admin.site.urls), ]
3. Reload the server using the python manage.py runserver command and verify the webpage.
4. When running the server, it will print the following system message on the console. From this message, we can observe the time at which the server was started, the version of the Django setup being used, and the HTTP link where the server is running.
Code:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
June 07, 2020 - 10:13:00
Django version 3.0.7, using settings 'educba.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Output:
Django View Rendered from Templates
The Templates are very helpful in understanding how the functionality of Django works. These templates hold the static items on an HTML page. It could be the Skelton of the page. To render a view from a template, the below steps are followed.
1. Create a Template Folder: The programmer can place all template-related HTML code in this folder. It is necessary to create the template folder within the primary project folder.
2. Tag the Template Folder in settings.py File: The created Template folder must be tagged in the settings.py file. So Once tagged, it allows every HTML file placed under the templates folder as accessible around the veiws.py file.
Code:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Template_DIR = os.path.join(BASE_DIR,'Templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Template_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]Template_DIR = os.path.join(BASE_DIR,'Templates')
3. Place an HTML file inside the Templates Folder
Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
</head>
<body>
<h1> Hello world from HTML page <h1>
</body>
</html>
4. Render the HTML File in views.py using() Method: The render function of Django is used to give the newly created HTML content to The render method combines a template with the context dictionary to return a HttpResponse object.
Syntax:
render(request, template_name, context=None, content_type=None, status=None, using=None)
Arguments | Description |
Request | This is used to generate a response. This is a mandatory argument. |
Template Name | Name of the template used for this view. This is a mandatory argument. |
Context | A context is a dictionary that maintains a mapping of variable names to their corresponding values. By default, this is an empty dictionary. So if the key is passed, the dictionary can retrieve and render the corresponding value. This is an optional argument. |
content_type | MIME(Multipurpose Internet Mail Extensions) to be used. The default value is ‘text/html’. This is an optional argument. |
Status | The response code to be used. The default response code is 200. |
Using | This argument represents the name of the template engine used to load the template. This is an optional argument. |
Code:
from django.shortcuts import render
from django.http import HttpResponse
def index(request_iter):
return render(request_iter,'design.html')
5. Reload the server using the python manage.py runserver command and verify the webpage.
Output:
Django view Rendered from Template TAG
Developers use template tags to inject dynamically generated content into the Django views. This is among the key functionalities of the template tag. They could flexibly inject dynamic content into the file.
Code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
</head>
<body>
<h1> Hello world from HTML page <h1>
{{ Key1 }}
</body>
2. Add a context template dictionary in the view and tag the dictionary to the context.
Code:
from django.shortcuts import render
from django.http import HttpResponse
def index(request_iter):
dict_Var = {"Key1" : "The Template tag value is rendered with reference to key1"}
return render(request_iter,'design.html',context=dict_Var)
Output:
Conclusion – Django Views
Django, the most predominant method for web-based applications, firmly implements the concept of views within its framework. These views can generate responses in the most flexible way possible. Concepts like templates and template tag processes in Django views add additional stability, making it one of the most predominantly used web application frameworks.
Recommended Articles
We hope that this EDUCBA information on “Django Views” was beneficial to you. You can view EDUCBA’s recommended articles for more information.