Thursday, 14 July 2022

Python django class views vs function views

 https://stackoverflow.com/questions/14788181/class-based-views-vs-function-based-views


Class view advantage:

The single most significant advantage is inheritance. On a large project it's likely that you will have lots of similar views. Rather than write the same code again and again, you can simply have your views inherit from a base view.



Function view implementation :

http://www.learningaboutelectronics.com/Articles/Function-based-views-in-Django.php#:~:text=Function%2Dbased%20views%20are%20views,template%20file%20into%20a%20view.


views.py File

from django.http import HttpResponse


def view1(request):

    return HttpResponse("<h1>View 1</h1>")


def view2(request):

    return HttpResponse("<h1>View 2</h1>")


def view3(request):

    return HttpResponse("<h1>View 3</h1>")


urls.py File

from django.conf.urls import url

from . import views


urlpatterns = [

    url(r'^view1', views.view1, name='view1'),

    url(r'^view2', views.view2, name='view2'),

    url(r'^view3', views.view3, name='view3'),


]



Anorther implementation of urls.py file
. means current dir

from .views import view1, view2, view3

urlpatterns = [
    url(r'^view1', view1, name='view1'),
    url(r'^view2', view2, name='view2'),
    url(r'^view3', view3, name='view3'),

]



No comments:

Post a Comment