[Fixed]-Good Practice: Organizing views.py in Django Apps

26👍

There is no problem with having multiple files containing views and models.

In fact all you need is module views and module models. In python the module is either file that ends with .py or folder that contains file __init__.py.

The app can look something like:

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

The models/__init__.py should look similar to code below (for submodules to be looked up by django at all).

from some_model import SomeModel
from some_other_model import SomeOtherModel

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

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

Check out the related doc entry.

Update:

The development version docs say you won’t have to define app_label in this case any more starting with 1.7 release.

Afterword:

In fact if you need to do that it usually means your app is too big and you should split it into several apps. Most people who come to django are afraid of having many small apps. The more third party apps you read through the more you realize app should solve one and only one problem. In your example having app milestones seems perfectly legit.

Leave a comment