1. Django如何新建一个网站
python django-admin.py startproject mysite
在mysite文件夹下会生成如下文件:
mysite/ manage.py mysite/ settings.py urls.py __init__.py wsgi.py
启动网站
python manage.py runserver
python manage.py runserver 8080 #修改端口号,默认的是8000
python manage.py runserver 0.0.0.0:8000 #告诉服务器去监听任意端口
2. Django是怎么工作的
1. 进来的请求转入/hello/;
2. Django通过settings.py中ROOT_URLCONF配置来获得URLconf;
3. Django在URLconf中的所有URL模式中,查找第一个匹配/hello/的条目;
4. 如果找到,调用相应的视图
5. 视图函数会返回一个HttpResponse对象
6. Django转换HttpResponse为一个适合的HTTP response, 以Web page显示出来
3. Django的View
添加网页,需要修改两个文件。一是urls.py,二是views.py。urls.py将url和view中的函数对应。views定义函数,返回httpresponse对象。
动态URL。比如./time/plus/3/、./time/plus/4/、./time/plus/5/ ...这种,需要再urls.py中添加正则表达式来匹配这种URL,前面的URL可以用如下正则表达式表达
(r'^time/plus/(\d{1,2})/$', hours_ahead)
在views.py中添加hours_ahead(httprequest, offset)。注意这里offset会从匹配的URL里提取出来的。并且要转换为str。
4. 贴出代码:
views.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# _*_ coding:utf-8 _*_ from django.http import HttpResponse import datetime def hello(request): return HttpResponse("Hello World!") def date(request): return HttpResponse("<html><body>It is " + str(datetime.datetime.now()) + ".</body><html>") def hours_ahead(request, offset): #这里的offset会自动从匹配的URL中获得 try: offset = int(offset) except ValueError: raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours = offset) html = "<html><body>In %d hour(s), it will be %s.</body></html>" % (offset, dt) return HttpResponse(html)
urls.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# _*_ coding:utf-8 _*_ from django.conf.urls import patterns, include, url from mysite.views import * # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', ('^hello/$', hello), ('^time/$', date), ('^time/plus/(\d{1,2})/$', hours_ahead), #/time/plus/3/这种URL # Examples: # url(r'^$', 'mysite.views.home', name='home'), # url(r'^mysite/', include('mysite.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)), )