What are views in Django

Views are very important in Django project. It contains complete project's business logic. Views also works as a mediator between models (database classes) and templates (HTML UIs). Views are bind with URLs, so whenever a user hits a URL based on URL and views mapping, appropriate view function and classed gets called. We can create views with two ways, first we can create functional views and second we can create class based views. Examples of views are mentioned below Class Based Views


#studentdetails.py   # view class
from django.views import View
from django.http import HttpResponse

class StudentDetails(View):
    def get(self, request):
        return HttpResponse("StudentDetails View Example!")
URL mapping

#urls.py   # url mapping example
from django.urls import path
from student.views.studentdetails import StudentDetails

urlpatterns = [
    path('student_details', StudentDetails.as_view(), name="student_details"),
]
Function Based Views

#studentdetails.py   # view class
from django.http import HttpResponse

def studentdetails_view(request):
    return HttpResponse("studentdetails_view example")
URL mapping

#urls.py   # url mapping example
from django.urls import path
from student.views import studentdetails

urlpatterns = [
    path('student_details', studentdetails.studentdetails_view, name='studentdetails_view'),
]