Django是典型的MVC框架,它的View須要templates來支持。用一句話能夠總結出Django開發:html
Getting data from the database according to a parameter passed in the URL, loading a template and returning the rendered template.sql
接下來看一下怎麼在Django中配置模板。django
在polls同級目錄新建文件夾templates
,在templates下新建admin
文件夾。將Django自帶文件django/contrib/admin/templatesadmin/base_site.html拷到此目錄下。文件結構以下:瀏覽器
├── db.sqlite3 ├── manage.py ├── mysite │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ ├── urls.pyc │ ├── wsgi.py │ └── wsgi.pyc ├── polls │ ├── admin.py │ ├── admin.pyc │ ├── __init__.py │ ├── __init__.pyc │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0001_initial.pyc │ │ ├── __init__.py │ │ └── __init__.pyc │ ├── models.py │ ├── models.pyc │ ├── tests.py │ ├── views.py │ └── views.pyc └── templates └── admin └── base_site.html
在mysite/setting中添加框架
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
指明模板路徑。函數
{% extends "admin/base.html" %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1> {% endblock %} {% block nav-global %}{% endblock %}
這些{% %}
模板語言最終會被轉換爲HTML頁面。url
接下來是在polls/views
中增長更多的函數,一個函數對應於瀏覽器中的一個url的功能。code
首先須要在polls下新建文件配置文件urls.py
sqlite
from django.conf.urls import patterns, url from . import views urlpatterns = patterns('', # ex: /polls url(r'^$', views.index, name='index'), # ex: /polls/5/ url(r'^(?P<question_id>\d+)/$', views.detail, name='detail'), # ex: /polls/5/results url(r'^(?P<question_id>\d+/result/$)', views.result, name='result'), )
而後在mysite下修改配置文件 mysite/urls.py,包含進來polls應用的配置文件htm
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^polls/', include('polls.urls')), )
from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("titus, huang") def result(request, question_id): response = "You are looking at the results of question %s." return HttpResponse(response % question_id) def detail(request, question_id): return HttpResponse("You are looking at question %s." % question_id)
在views.py
中增長result
,detail
函數。
在瀏覽器中輸入
http://127.0.0.1:8000/polls/6/ http://127.0.0.1:8000/polls/6/result/
便可看到對應的響應。