django中app分组
08.13自我总结
django中app分组
一.django路由系统app进行分组
1.创建app
- 使用pycharm创建django的时候, 加上app的名字,后续多个app只需复制粘贴之前app整个文件即可
- 命令行Python manage.py startapp app的名字
2.app内文件简介
migrations
:模型操作的迁移文件admin.py
:django admin的时候会用apps.py
:注册文件models.py
:写表生成的代码tests.py
:测试文件views.py
:视图文件,一般业务逻辑会写在其中urls.py
:格式与主urls.py一样复制过来即可
3.include用于主路由和分路由连接
主urls,py:
from django.conf.urls import url, include
urlpatterns = [
url(r'^classes/', include("classes.urls")),
url(r'^staudent/', include("staudent.urls")),
url(r'^teachers/', include("teachers.urls")),#app名称.urls
]
分urls.py:
from django.conf.urls import url
from classes import views
urlpatterns = [
url(r'^get_classes/', views.get_classes) #其域名为/classes/get_classes/
#而不是/get_classes/
]
4.路由的分发
正则表达式匹配
urlrouters:
url(r'^test/(\w+)/(\w+)/', views.test),
url(r'^test1/(?P<id>\w+)/(?P<name>\w+)/', views.test1),
views.py:
def test(request, name, id):
print(id, name)
return HttpResponse('test')
def test1(request, name, id):
print(id, name)
return HttpResponse('test')
注意:
- 如果没有?P的约束, 传参的时候, 会根据顺序来获取参数对应的值
- 而如果有约束的话, 传参的时候, 会固定的将获取的值传给所对应的的约束
自定制404notfound的页面:
url(r'^', views.notfound),
views:
def notfound(request);
return render(request, "404.html")
5.利用正则表达式以及name关键字反向路由
urls.py:
url(r'^login.*?/', views.login, name='xxx'),
login.html:
<form action="{% url "xxx" %}" method="post">
<input type="text">
</form>
当我们输入url 为loginXXXXXXXXXXXXXX的时候网页上form表单的url会自动变成login
如果url(r'^login11', views.login, name='xxx'),上form表单的url会自动变成login11