django复习笔记3:urls/views/templates三板斧
0.先看看文件结构
sh-3.2# tree -L 2 mysite/ mysite/ ├── __pycache__ │ └── manage.cpython-34.pyc ├── blog │ ├── __init__.py │ ├── __init__.pyc │ ├── __pycache__ │ ├── admin.py │ ├── admin.pyc │ ├── migrations │ ├── models.py │ ├── models.pyc │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── create_data.py ├── db.sqlite3 ├── manage.py ├── mysite │ ├── __init__.py │ ├── __init__.pyc │ ├── __pycache__ │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ └── wsgi.py └── templates 8 directories, 19 files
1.urls.py
去耦合最好的办法就是用project的urls来管理app的urls
###project中的urls.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'',include('blog.urls')), )
###app中的urls.py from django.conf.urls import patterns, url from blog import views urlpatterns = patterns('', url(r'^$', views.post_list), )
可以看到url(r'',include('blog.urls'))指向blog的urls,而app中的url(r'^$', views.post_list)指向了views的post_list函数。
2.views.py
from django.shortcuts import render# Create your views here. def post_list(request): return render(request,'post_list.html',{})
可以看到views.py指向了post_list.html这个templates的页面
3.templates
将templates模板设置到app的根路径里,配置如下
TEMPLATE_PATH = os.path.join(BASE_DIR, 'blog/templates') TEMPLATE_DIRS = [ TEMPLATE_PATH, ]
其中BASE_DIR可以通过设置断点来查看到具体路径。