How to split views.py to several smaller files in Django
When your views.py
is too large, it becomes much more difficult to manage your code. So you might want to split views.py
into several subviews, each of which contains a single sort of views.
To split views.py
, you could follow the following steps. Your original views.py
might look like this:
import ...
def view1(request):
pass
def view2(request):
pass
Now, create a new folder subviews
aside with views.py
, i.e. /Django/mysite/MyAPI/subviews
. Next, create __init__.py
, viewsa.py
, and viewsb.py
in the folder subviews
to form the following folder/file structure :
subviews/
__init__.py
subviews1.py
subviews2.py
subviews1.py :
from .views import *
def view1(request):
pass
subviews2.py :
from .views import *
def view2(request):
pass
__init__.py :
from subviews1 import *
from subviews2 import *
Then this would work the same as a single views.py
file. Don't forget to change the urls.py
file before you reloading Django.
0 人喜欢
There is no comment, let's add the first one.