django view太大,切分到不同的目录

(新增目录下面一定得有__init__.py,    方法1,需要修改__init__.py,  方法2可以将__init__.py 保持为空)

备注:view 子目录引用model, 可用 from app_name.models import * 方式引用, 记得加上 app_name

方法1:

Remove the views.py file and create a directory named views. Add a __init__.py file inside it and create the separated view files.

|∙∙core/
  |∙∙__init__.py
  |∙∙admin.py
  |∙∙migrations/
  |∙∙models.py
  |∙∙tests.py
  |∙∙urls.py
  |∙∙views/
    |∙∙__init__.py
    |∙∙alpha.py
    |∙∙beta.py

views/__init__.py

This is an important step: import all the modules inside each view file.

from .alpha import *
from .beta import *

views/alpha.py

from django.shortcuts import render

def view_a(request):
    return render(request, 'view_a.html')

def view_b(request):
    return render(request, 'view_b.html')

views/beta.py

from django.shortcuts import render

def view_c(request):
    return render(request, 'view_c.html')

def view_d(request):
    return render(request, 'view_d.html')

urls.py

You don’t need to change anything here.

from django.conf.urls import url
import .views

urlpatterns = [
    url(r'^aaa$', views.view_a, name='view_a'),
    url(r'^bbb$', views.view_b, name='view_b'),
    url(r'^ccc$', views.view_c, name='view_c'),
    url(r'^ddd$', views.view_d, name='view_d'),
]

方法2:

Remove the views.py file and create a directory named views. Add a __init__.py file inside it and create the separated view files.

|∙∙core/
  |∙∙__init__.py
  |∙∙admin.py
  |∙∙migrations/
  |∙∙models.py
  |∙∙tests.py
  |∙∙urls.py
  |∙∙views/
    |∙∙__init__.py
    |∙∙alpha.py
    |∙∙beta.py

views/alpha.py

from django.shortcuts import render

def view_a(request):
    return render(request, 'view_a.html')

def view_b(request):
    return render(request, 'view_b.html')

views/beta.py

from django.shortcuts import render

def view_c(request):
    return render(request, 'view_c.html')

def view_d(request):
    return render(request, 'view_d.html')

urls.py

You don’t need to change anything here.

from django.conf.urls import url
import .views

urlpatterns = [
    url(r'^aaa$', views.view_a, name='view_a'),
    url(r'^bbb$', views.view_b, name='view_b'),
    url(r'^ccc$', views.view_c, name='view_c'),
    url(r'^ddd$', views.view_d, name='view_d'),
]





This entry was posted on 2018 年 03 月 19 日 and is filed under IT DOC. Written by: . You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.