1.創(chuàng)建一個(gè)項(xiàng)目
django-admin.py startproject HelloWorld
2.進(jìn)入HelloWorld項(xiàng)目,在manage.py的同一級(jí)目錄,創(chuàng)建templates目錄,并在templates目錄下新建404.html,500.html兩個(gè)文件。
3.修改settings.py
(1.)DEBUG修改為False,(2.)ALLOWED_HOSTS添加指定域名或者IP,(3.)指定模板路徑 ‘DIRS' : [os.path.join(BASE_DIR,‘templates')],
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
# SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ 'localhost' , 'www.example.com' , '127.0.0.1' ] TEMPLATES = [ { 'DIRS' : [os.path.join(BASE_DIR, 'templates' )], 'APP_DIRS' : True , 'OPTIONS' : { 'context_processors' : [ 'django.template.context_processors.debug' , 'django.template.context_processors.request' , 'django.contrib.auth.context_processors.auth' , 'django.contrib.messages.context_processors.messages' , ], }, }, ] |
4.新建一個(gè)views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
from django.http import HttpResponse from django.shortcuts import render_to_response from django.views.decorators.csrf import csrf_exempt @csrf_exempt def hello(request): return HttpResponse( 'Hello World!' ) @csrf_exempt def page_not_found(request): return render_to_response( '404.html' ) @csrf_exempt def page_error(request): return render_to_response( '500.html' ) |
5.修改urls.py,代碼如下
1
2
3
4
5
6
7
8
9
|
from django.conf.urls import url from django.contrib import admin import HelloWorld.views as view urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test$', view.hello), ] handler404 = view.page_not_found handler500 = view.page_error |
重新編譯,重啟uwsgi,輸入localhost/HelloWorld/test,顯示'Hello World!',輸入其它地址會(huì)顯示404.html內(nèi)容,如果出錯(cuò)則顯示500.html內(nèi)容。
原文鏈接:http://www.yoyong.com/archives/987