Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 428
Mathyou Avatar asked Aug 10 '17 16:08

Mathyou


People also ask

Where do I put form py?

You have created forms.py inside users/templates/users directory. It should be in users/ that means where views.py, models.py and other files are located, so move it to the correct directory and let me know.

What does forms py do in Django?

forms.py is where the django documentation recommends you place all your forms code; to keep your code easily maintainable. Also, since its a convention mentioned in the documentation, it helps when you are collaborating with others because that is where others will expect to look for your code dealing with forms.

What is form Cleaned_data?

form. cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).


1 Answers

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.

like image 126
Siegmeyer Avatar answered Sep 25 '22 01:09

Siegmeyer