按照惯例,做一个helloworld吧
首先是创建一个项目
1.在你想要放置项目的目录下输入
django-admin.py startproject newsite
此时目录下就生成newsite这个项目了
在newsite目录下含有manage.py和另一个newsite目录
在newsite目录下有__init__.py, settings.py, urls.py, wsgi.py
2.编写视图函数
值得注意点是,名字一般都是根据需要命名的,这里就用views.py了
在最深都那个newsite目录下创建views.py
from django.http import HttpResponse
def hello(request):
return HttpResponse("hello world")
3.url与视图函数映射
django的机制是通过解析url找到对应的视图函数对象,而不是找的相应目录,这样灵活性就很高了。一般我们会用正则表达式来解析url
在urls.py中添加代码
from django.conf.urls import patterns, include, url
from mysite.views import hello
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# 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)),
('^hello/$',hello),
)
4.测试下我们都劳动成果吧。
在项目newsite目录下,即含有manage.py的那个目录
输入sudo python manage.py runserver 0.0.0.0:1234
这样同局域网上的主机都可以访问这个ip的1234端口了
自己访问自己所127.0.0.1:1234/hello/