上一篇通过“django-admin startproject helloworld”是创建项目,一个项目下可以有多个应用(app).打开cmd,cd到manage.py所在目录使用如下指令创建一个应用
python manage.py startapp hello
新建成功后,生成的目录结构如下
─helloworld
│ db.sqlite3
│ manage.py
│
├─hello
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ views.py
│ │ __init__.py
│ │
│ ├─migrations
│ │ __init__.py
│
└─helloworld
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
新建应用后,一定要在setting.py脚本里面,把刚才新建的应用名称添加到INSTALLED_APPS里,要不然无法识别到新增的这个应用,如下最后一行。
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello'
]
在hello目录下新建一个templates包,再新建一个demo.html文件,写入以下内容
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo样式</title>
</head>
<body>
</body>
</html>
关于html相关语法学习,可以参考这个网站【http://www.runoob.com/html/html-tutorial.html】
视图与urlhtml的内容页面有了,接下来就是如何能让他在指定的url地址上展示出来了,在hello/views.py里写视图函数
在hello/views.py里写视图函数,把上一篇新建的view.py里面的内容全部统一放到hello/views.py下管理
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("Hello world ! django ~~")
def demo(request):
return render(request, 'demo.html')
在helloworld/urls.py里添加url访问路径
from django.conf.urls import url
from hello import views
urlpatterns = [
url('^$', views.index),
url('^demo$', views.demo)
]
接下来在浏览器输入地址:http://127.0.0.1:8000/demo就能访问到demo.html页面啦