django下载安装
下载:pip install django==1.11.9
创建项目
django-admin startproject qingqing
cd qingqing
启动项目:python manage.py runserver 127.0.0.1:8001
cd qingqing
创建app:python manage.py startapp xiaoqing
需要在项目的配置文件settings.py中添加一个app的配置
INSTALL_APPS = [
'xiaoqing', app名称
]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 以下两种写法都可以
'app01.apps.App01Config',
#'app01',
]
两个框架模式
MVC
M:models数据库相关
V:views 视图逻辑相关
C:controller控制器 url分发 不同的路径找到不同的视图函数
MTV
M:models数据库相关
T:templates模板 ,HTML文件
V:views 视图逻辑相关
+ url控制器 不同的路径找到不同的视图函数
MVVM 后面介绍
url配置
urls.py文件中写在urlpatterns = []中
简单的路由
from app01 import views
url(r'^index/',views.index),
无名分组
url(r'^index/(\d+)/(\d+)/',views.index), --- def index(request,n,m) 位置参数
有名分组
url(r'^index/(?P<year>\d+)/(?P<month>\d+)/',views.index), -- def index(request,year,month) 关键字参数,参数顺序不要求
url(r'^index/$',views.index),
url(r'^index/(?P<num>\d+)/,views.index),
视图函数参数默认值,
def index(request,num='1'):
print(num)
url路由分发之include
项目文件夹下的urls.py文件中的url写法:
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
urlpatterns = [
# url(r'^admin/', admin.site.urls),
#首页
url(r'^$', views.base),
url(r'^app01/', include('app01.urls')),
url(r'^app02/', include('app02.urls')),
]
app01下urls.py内容写法
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^$', views.app01base),
url(r'^index/', views.index),
]
app02下urls.py内容写法
from django.conf.urls import url
from django.contrib import admin
from app02 import views
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^$', views.app02base),
url(r'^home/', views.home),
]