How Create Views in Django

Educations 2 Fri 22 Jul 2022
How Create …

Django working  as M – Model,  V – View and T – Template 

View create two type  

  • Function Based View
  • Class Based View

Function Based View

A function based view, is a Python function that takes a Web request and returns a Web response.

This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image or anything.

Each view function takes an HttpRequest object as its first parameter.

The view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object.

We will call these functions as view function or view function of application or view.

Syntax:-

def function_name (request):  
  return HttpResponse(‘html/variable/text’)

Function Based Views

Syntax:-

def function_name (request):
  return HttpResponse(‘html/variable/text’)

Where HttpResponse is class which is in django.http module so we have to import it before using HttpResponse

views.py

from django.http import HttpResponse
def django(request):
return HttpResponse(‘Hello Django’)

example1
def django1(request):
a = ‘<h1>Hello Variable</h1>’
  return HttpResponse(a)


def python(request):
  return HttpResponse(‘<h1>Hello Python</h1>’)

example2

def django2(request):
a = 10 + 10
  return HttpResponse(a)

Function Based Views

Single Application with Single view function

views.py

from django.http import HttpResponse

def exampl1(request):

  return HttpResponse(‘Hello Django’)

urls.py

urlpatterns = [

  path(‘admin/’, admin.site.urls),

  path(‘exm/’, views.exampl1),

]

Single Application with multiple view functions.

views.py

from django.http import HttpResponse

def exampl1(request):

  return HttpResponse(‘Hello Django’)

def exampl1(request):

  return HttpResponse(‘<h1>Hello Python</h1>’)

urls.py

urlpatterns = [

   path(‘urlname1/’, views.exampl1),

  path(‘urlname2/’, views.exampl2),

]

 

********************************

  • Create Django Project: django-admin startproject project_name
  • Change Directory to Django Project: cd project_name
  • Create Django Application: python manage.py startapp app_name
  • Add/Install Application to Django Project (course to geekyshows) using settings.py file
    INSTALLED_APPS = [‘django.contrib.admin’,‘app_name, ]
  • Write View Function inside views.py file
  • Open views.py
  • Import HttpResponse class from django.http module

  from django.http import HttpResponse

  • Write view Function

  def exampl1(request):

  return HttpResponse(‘Hello Django’)

 Save views.py

************************

--Posted By : santosh


Back to Post
Comments....

All Comments...

No comments yet !!!!

Bestsaller

Online Store


Populer Store
Electronics Store
Services Store
Other Services