What is the best way to organize views in Django?

Asked

Viewed 430 times

2

I have views.py in my study project where I group it from methods to represent views (methods that return Httpresponse), to generic views based on class (such as Detailview, Listview).

I was thinking: what are the best practices to organize the views referring to a certain model without spreading them through an entire file? I can somehow group them into a single class and organize my file?

  • I took a look here if there was no problem in doing the following: grouping all methods that return Httpresponse referring to my model into one class and make them static. I did it and it worked. Is there any problem in doing it from a technical point of view?

  • Good question :)

1 answer

4


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

original views.py 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 that 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.

  • That’s right Arthur. Just in terms of organization, after all everything is working perfectly.

  • Arthur today realized that really the best way to organize my views is as you said above. I was making classes with other internal classes, but due to some problems like accessing values of the most external class, I saw that its solution would be the most interesting. Thank you so much for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.