Mat*_*you 4 python forms django project-structure project-structuring
我现在开始写我的第一个Django项目,我需要forms.py为应用创建文件。我看过一些教程将文件存储在项目的主文件夹下,而另一些则存储在app目录中。
如果我想制作仅适用于一个应用程序的表单,哪种布局最适合我?
是否可以制作多个文件来保存表单代码?
谢谢!
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
|
...
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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.
| 归档时间: |
|
| 查看次数: |
836 次 |
| 最近记录: |