Good practice: organizing views.py in Django applications

I am learning Django. My experience with PHP and Java with experience using Model View Controller frameworks. I always had a separate file for each of my views, models, and templates, but only one view.py and models.py are mentioned in the Django tutorial.

Everything seems to be in order if you have a small application - what if you want to organize your views and models according to their purpose? For example, the "Projects" and "Milestones" views. I hope you don't have to create another Python package (application) for each viewer:

python manage.py startapp projects

python manage.py startapp milestones

I can assume that you could have a file milestones.py and project.py for your views and models instead of common views.py and models.py? Then models can be imported, when necessary, into representations, and requests are routed to certain representations?

+8
python django views models
source share
1 answer

There are no problems with having multiple files containing views and models.

In fact, all you need is a views module and module models . In python, a module is either a file ending with .py or a folder containing the __init__.py file.

An application might look something like this:

 app_folder - views | - __init__.py | - some_view.py | - some_other_view.py - models | - __init__.py | - some_model.py | - some_other_model.py 

models/__init__.py should look something like the one shown below (for submodules that need to be looked at django in general).

 from some_model import SomeModel from some_other_model import SomeOtherModel 

The only difference from the general approach is to have the app_label defined in the models:

 class SomeModel(models.Model): class Meta: app_label = 'app_folder' 

View the related doc entry.

Update:

The docs version says that you will not need to define app_label in this case, starting from version 1.7.

Afterword:

In fact, if you need to do this, this usually means that your application is too large and you should split it up into several applications. Most people who come to django are afraid to have many small applications. The more third-party applications you read, the more you realize that the application should solve one and only one problem. In your example, the app milestones seems completely legal.

+18
source share

All Articles