What is the best way to organize views in Django?

1

I have views.py in my study project where I group it from methods to represent views (methods that return HttpResponse), to generic class-based views (such as DetailView, ListView).

I was thinking: what are the best practices for organizing views for a particular model without spreading them across an entire file? Can I group them somehow into a single class and organize my file?

    
asked by anonymous 06.02.2015 / 00:52

1 answer

2

I'm trying to understand your question. If it's about the organization you can split your views.py into smaller modules if it gets too big.

views.py original follows below:

# (imports)
...

def view1(request):
    pass

def view2(request):
   pass

class IndexView(TemplateView):
    template = 'core/index.html'

index = IndexView.as_view()
...

You can have the same structure in a more organized way. Below is an example of how to modularize the same views.py.

views/
  __init__.py
  base.py
  cbvs.py

base.py:

# (imports)
...

def view1(request):
    pass

def view2(request):
   pass

...

cbvs.py:

# (imports)
...

class IndexView(TemplateView):
    template = 'core/index.html'

index = IndexView.as_view()

...

__ init__.py:

from base import view1
from base import view2
from cbvs import index

In addition, you can use this same structure to organize other large files in your Django project.

    
06.02.2015 / 03:08