Search code examples
pythondjangoformsproject-structureproject-structuring

Where should the forms.py file be located?


I'm starting to write my first Django project right now and I need to make my forms.py file for an app. I've seen some tutorials store the file under the main folder for the project and some in the app directory.

  1. Which layout is the best for me if I want to make a form that only applies to one app?

  2. Is it suitable to make more than one file to keep my forms code in?

Thanks!


Solution

  • Here is the standard layout:

    ├── apps/
    |    ├── [app]/
    |    |     ├── __init__.py
    |    |     ├── urls.py
    |    |     ├── models.py
    |    |     ├── forms.py # Forms
    |    |     ├── admin.py
    |    |     ├── views.py
    |    |     ├── migrations/
    |    |     ├── management/
    |    |     ├── templates/ # Here or in the project root
    |    |     └── (other)
    |    |
    |    └── __init__.py
    |
    ...
    

    In short: keep all forms relevant to the app in the app. It's conceptually consistent, intuitive and makes code more maintainable (by separation).

    Multi-app forms/components are rather rare. You can keep them in app named "common". This is a very popular convention.

    This way you can import forms into views without a hassle:

    from .forms import FormA, FormB
    # or 
    from . import forms
    # or
    from .forms import *
    # and from common:
    from ..common import forms as common_forms
    

    Regarding your second question: absolutely - if benefits of the separation (such clean project layout, maintainability, more verbose filenames) are worth the trouble (e.g. of importing multiple files instead of one). There are no hard rules, so you must calculate the trade-offs and decide.