Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - split view.py to small files

Tags:

django

I have big views.py where I have class based views and def views. It is possible to split it somehow to seal small files, so, for example, in one file I have only class based views, and in other file - functions

like image 231
Alexey K Avatar asked Mar 15 '26 14:03

Alexey K


2 Answers

Yes, there is not much special about views.py itself. You can implement two files for example:

# app/views_simpel.py

def view1(request):
    # ...
    pass

def view2(request):
    # ...
    pass

and another one:

# app/views_complex.py

def view3(request):
    # ...
    pass

def view4(request):
    # ...
    pass

In your urls.py you can then import those views, for example:

# app/urls.py

from django.urls import path

from app.views_simpel import view1, view2
from app.views_complex import view3, view4

urlpatterns = [
    path('view1/', view1),
    path('view2/', view2),
    path('view3/', view3),
    path('view4/', view4),
]

Both files can contain function-based views, class-based views, etc. In fact, the urls.py does not see much difference between the two, since by using .as_view() on a class-based view, you hand it a "dispatcher" function.

like image 66
Willem Van Onsem Avatar answered Mar 17 '26 03:03

Willem Van Onsem


Yeah. Not only views. models and forms/serializers as well.

Here's my preferred structure of an app.

-- app
---- models (package)
------ __init__.py
------ vehicle.py
------ trip.py

---- views (package)
------ __init__.py
------ vehicle.py
------ trip.py

Then you can normally import Class-based view in urls file like this

from app.views.vehicle import VehicleApiView

then customize your own routing scenario based on what's inside that view.

Same applies for models importing.

like image 44
Ramy M. Mousa Avatar answered Mar 17 '26 04:03

Ramy M. Mousa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!