第一课:视图显示

1   建立一个项目:django-admin startproject blog,

进入blog: cd blog

显示:blog(__init__.py settings.py urls.py ) manage.py

2,在当前目录,建立一个应用:django-admin startapp appblog

显示:appblog(__init__.py modules.py views.py tests.py) blog manage.py

3   配置应用vim blog/settings.py下的INSTALLED_APPS (‘appblog',)

编写响应vim blog/urls.py

url(r'^blog/index/$','blog.views.index'),

编写视图vim appblog/views.py:编写def文件,

from django.http import HttpResponse

def index(req):

return HttpResponse('<h1>hello world to Django!</h1>')

4启动项目:python manage.py runserver

第二课:模板映射

1 首先看结构图

Django开发网站(二)-LMLPHP

1 首先建立外框,即项目:django-admin startproject mysite

然后建立中间框,即应用和模板

django-admin startapp myapp

mkdir templates

2 编写最内框,即各文件

vi templates/index.html

 <html>
<body>
<meta http-equiv="Content-Type" content="text/html" />
<title>mytile my index</title>
</head>
<body>
<h1>mybody my index</h1>
</body>
</html>
~

vi mysite/urls.py

 from django.conf.urls import patterns, include, url

 # Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover() urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mytest.views.home', name='home'),
# url(r'^mytest/', include('mytest.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^myapp/',include('myapp.urls')),
)
~

vi myapp/urls.py

 from django.conf.urls import *

 urlpatterns = patterns('',
url('^index/$','myapp.views.index'),
)
~
~
~

vi myapp/views.py

 # Create your views here.
from django.shortcuts import render_to_response def index(req):
return render_to_response('index.html') ~
~

vi myapp/settings.py

 TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
#######################################
'/home/django/mytest/templates',
) INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
###############################
'myapp',
)

3 启动服务器并在浏览器测试
 python manage.py runserver

http://127.0.0.1:8000/myapp/index

4 解析运行原理:

当网页上要请求时,首先进入mysite/urls.py中,执行:

url(r'^myapp/',include('myapp.urls')),

再次调用myapp/urls.py中的文件,执行:

url('^index/$','myapp.views.index'),

接着进入myapp/views视图中的index函数,执行:

def index(req):
     return render_to_response('index.html')
这样就返回模板中的index.html文件,即执行templates/index.html

重要的地方:指向 include() 的正则表达式并不包含一个 $ (字符串结尾匹配符),但是包含了一个斜杆。每当 Django 遇到 include() 时,它将截断匹配的URL,并把【剩余】的字符串发往被包含的 URLconf 进一步处理。

django URL常用配置方法

05-11 15:36
查看更多