如下:
[root@centos2 HelloWorld]# ll
total 12
drwxr-xr-x 3 root root 4096 Aug 13 11:56 HelloWorld #创建的工程
-rwxr-xr-x 1 root root 542 Aug 11 09:32 manage.py #命令管理
drwxr-xr-x 4 root root 4096 Aug 13 11:57 polls #创建的app
进去到app里面看下目录结构如下:
[root@centos2 polls]# tree
.
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ ├── 0001_initial.py
│ ├── 0002_auto_20170813_0303.py
│ ├── 0003_auto_20170813_0326.py
│ ├── __init__.py
│ └── __pycache__
│ ├── 0001_initial.cpython-34.pyc
│ ├── 0002_auto_20170813_0303.cpython-34.pyc
│ ├── 0003_auto_20170813_0326.cpython-34.pyc
│ └── __init__.cpython-34.pyc
├── models.py
├── __pycache__
│ ├── admin.cpython-34.pyc
│ ├── __init__.cpython-34.pyc
│ ├── models.cpython-34.pyc
│ └── views.cpython-34.pyc
├── tests.py
└── views.py
其中最后一行views.py是我们真正写代码的地方,也就是传说中的视图,现在我们写一个视图:
root@centos2 polls]# cat views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def hello(request):
test="""<h1>this is my first web<h1> """
return HttpResponse(test)
视图写完成之后,要去工程目录下面的urls.py中进行添加,否则无效:
[root@centos2 HelloWorld]# cat urls.py
"""HelloWorld URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/dev/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from polls import views #从polls app中导入views视图,这里要是不导入polls的话会报错
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.hello), #调用视图中的hello函数
]
然后运行,结果如下: