非常重要:
创建了一个APP,一定要在setting.py INSTALLED_APPS = []中添加app的名字
编辑demo1/views.py
每个响应对应一个函数,函数必须返回一个响应
每一个响应函数,对应一个URL
from django.shortcuts import render
from django.http import HttpResponse
def index(request):#必须添加参数,接受请求
return HttpResponse('hello world!')#返回传回的字符串
配置django_demo/urls.py
url的三种写法:
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,include
from django.contrib import admin
import demo1.views as dv
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', dv.index),
浏览器中输入http://127.0.0.1:8000/index/,就可以看到’hello world!’
优化url的写法:
直接import demo1.views as dv
url(r’^index/’, dv.index),
如果网站有多个应用,把所有url都写在根url文件中,十分繁琐,会url名称冲突等问题。
from django.conf.urls import url,***include***
from django.contrib import admin
# import demo1.views as dv
urlpatterns = [
url(r'^admin/', admin.site.urls),
***url(r'^index/', include('demo1.urls')),***
]
在APP文件(demo1)文件夹下添加urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^1/$', views.index),#用^$约束
]
在浏览器中输入127.0.0.1:8000/index/1,就可以看到’hello world!’
其他注意问题:
1、_ init _.py声明模块的文件,一般为空。django_demo目录就变成一个模块,可以直接在代码引用。例如:WSGI_APPLICATION = ‘django_demo.wsgi.application’,就是把django_demo当成一个模块
2、static文件夹中放(CSS, JavaScript, Images)
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
3、
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',#表示django自带的模板
}
]
为解决的问题:为啥加中文注释就报错???加#-*-coding:utf-8 -*-没用