Users Online

· Guests Online: 46

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Articles Hierarchy

Django Tutorial

Django Views

Django Views

Introduction to Django Views

All views for a Django application are placed in 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 hold anything subjective in logic is essential to go back as a response. The code can be placed anywhere needed until it is associated with the python path. Every view is callable and holds the capability to 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 views.py file of the Django Application 

For Declaring the view in Django we need to have an HTTP request and a response. The HTTP request will be automatically created by the Django framework. the response for this request needs to be created by the programmer. This response will be placed in the HttpResponse() method of Django.http package. HttpResponse has subclasses counting Streaming HttpResponse , JsonResponse  and FileResponse.

Every function created in this views.py file will be considered as 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 url mentioned here will be used for reaching the web page which is been mentioned.

  • 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 python manage.py runserver command and verify the webpage.

4. On running the server the below-mentioned system message will be printed on to the console, from the given message we can notice the time at which the server was kickstarted, the version of the Django setup which is been used, and the HTTP link at which the server is kickstarted.

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 Views Example 1

Django Views Example 2

Django View Rendered from Templates

The Templates are very helpful in understanding how the functionality of Django works. these templates hold the static items in 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:  All template related HTML code could be placed into this folder. The template folder has to be created under the primary project folder.

Template Folder Example 3

2. Tag the Template Folder in settings.py File:  The created Template folder needs to be tagged in 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 variable name and variable value mapping maintained as a dictionary. In default, this is an empty dictionary. So if the key is passed the corresponding value from the dictionary can be retrieved and rendered. 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 is used to represent the name of the template engine used for loading 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 python manage.py runserver command and verify the webpage.

Output:

Django Views Example 4

webpage Example 5

Django view Rendered from Template TAG

The template tags are used for injecting dynamically generated content to the Django views. This is among the key functionalities of the template tag. They could flexibly inject dynamic contents 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:

Rendered from Template  TAG Example 6Rendered from Template  TAG Example 7

Conclusion

Django being the most predominant method for web-based applications. the concept of views are very firmly implied in a Django framework such that these views could generate responses in the most flexible way possible. Concepts like templates and template tag processes in Django views add additional stability set up in making it as one among the most predominantly used web application framework.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.71 seconds
10,841,650 unique visits