Examples


Django Views


What is Views

  • Django views that takes http requests and returns http response.
  • A Django view can be a Python function or a class-based view that handles multiple HTTP methods.
  • This response can be the HTML documents, or a redirect, or a 404 error.
  • All view function are created inside the views.py placed for your app`s folder.

Types of Views

  • Function-based Views
  • Class-based Views

1. Function-Based Views

myproject/myapp/views.py
from django.http import HttpResponse

def index(request):
    return HttpResponse("Welcome To Django")
    
def about(request):
    return HttpResponse("<h1>This is about us page</h1>")
    
def contact(request):
    return HttpResponse("<h5>This is Contact us page</h5>")

URL configuration : To map a view to a URL, we need to configure in the myproject/myapp/urls.py file:

from django.urls import path
from .import views

urlpatterns = [
    path("",views.index,name='index'),
    path("about/",views.about,name='about'),
    path("contact/",views.contact,name='contact'),
]

2. Class-based Views

myproject/myapp/views.py
from django.http import HttpResponse
from django.views import View

class IndexView(View):
    def get(self, request):
        return HttpResponse('Hello world!')

URL configuration : To map a view to a URL, we need to configure in the myproject/myapp/urls.py file:

from django.urls import path
from .views import IndexView

urlpatterns = [
    path('', IndexView.as_view(), name='index'),
]

Prev Next