[Django]-Django – split view.py to small files

4👍

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.

4👍

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.

1👍

Of course, if you want you can make different file for functions. Then you just need to import them in you views.py file for your classes.

Leave a comment