参考资料:http://www.ziqiangxuetang.com/django/django-tutorial.html
所用python版本为2.7.9
django版本为1.8.16
平台:Windows8.1工业版
本文为纯手工搭建环境,也就是命令行+编辑器(Atom或VsCode)
安装好python环境后
配置环境变量
PATH=E:\Program Files\Python27\Scripts;E:\Program Files\Python27\;
注意:如果装过LoadRunner,这两项会和pip会有冲突
要把python的放到最前面才行
E:\Program Files (x86)\HP\LoadRunner\strawberry-perl\perl\bin\pip
E:\Program Files (x86)\HP\LoadRunner\strawberry-perl\perl\bin\pip.bat
在win下使用where pip即可看到pip命令执行的实际程序
机智如我23333
新建项目
django-admin.py startproject testproject
执行过后在当前文件夹下会多出manage.py和一个testproject文件夹
文件夹内部为__init__.py
、settings.py
、urls.py
、wsgi.py
新建 app
django-admin.py startproject testname
或者执行刚刚生成的manage.py
python manage.py startproject testname
执行后多出一个testname文件夹
内部为__init__.py
、admin.py
、models.py
、tests.py
、views.py
同时在settings.py中更新INSTALLED_APPS
同步数据库
python manage.py syncdb
注意:Django 1.7.1及以上的版本需要用以下命令
python manage.py makemigrations
python manage.py migrate
启动项目
默认监听8000
python manage.py runserver 8000
清空数据库
python manage.py flush
创建管理员
python manage.py createsuperuser
# 按照提示输入用户名和对应的密码就好了邮箱可以留空,用户名和密码必填
修改密码
python manage.py changepassword username
数据迁移
python manage.py dumpdata appname > appname.json
python manage.py loaddata appname.json
项目终端
python manage.py shell
安装bpython
pip install bpython
数据库终端
python manage.py dbshell
大致流程分析
服务器启动后
通过wsgi.py
中指定的settings文件读取项目配置并加载所有模块
urls作为网址分发器匹配用户的HTTP请求分配到指定的模板上(即业务逻辑层)
然后再调用模板引擎绘制html返回
所以,在views.py
中增加
0 1 2 3 4 5 |
#coding:utf-8 from django.http import HttpResponse def index(request): return HttpResponse(u"helloworld") |
更新urls.py
0 1 |
from testname import views as test1_views # 先引入 |
再使用
0 1 |
url(r'^$', test1_views.index), |
注意这时候没有单引号
或者直接写
0 1 |
url(r'^$', 'testname.views.index'), |
这个index对应views中的index方法
模板渲染
为了方便更改url格式,可以动态渲染页面中的url
在views.py中这么写
0 1 2 3 4 |
from django.shortcuts import render def testurl(request): return render(request, 'test.html') |
在testname文件夹下新建templates文件夹
新建test.html,内容为
0 1 2 3 4 5 6 7 8 9 10 11 |
<!DOCTYPE html> <html> <head> <title>testurl</title> </head> <body> <a href="{% url 'testurl' %}">{% url 'testurl' %}</a> </body> </html> |
注意:{%url (只有这个空格是必需的)’name’%}
在urls.py中这么写
0 1 |
url(r'^testurl/$', 'testname.views.testurl', name='testurl'), |
这样就能动态渲染url了
在代码中写法为
0 1 2 |
from django.core.urlresolvers import reverse reverse('testurl', args=(xxxxxxx)) |
另外
获取HTTP参数写法为
0 1 |
value = request.GET['key'] |
模板引擎
在代码中传入变量
0 1 2 |
varible = 2333 render(request, 'test.html' ,{'key':varible }) |
在html中显示变量
{{key}}
循环
{% for i in TutorialList %}
{{ i }}
{% endfor %}
block继承和文件引用
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html> <head> <title>{% block title %}默认标题{% endblock %}</title> </head> <body> {% include 'nav.html' %} {% block content %} <div>这里是默认内容,所有继承自这个模板的,如果不覆盖就显示这里的默认内容。</div> {% endblock %} {% include 'bottom.html' %} </body> </html> |
其中include可以套用其他模板
block可以被子模板继承覆盖
继承写法为
{% extends ‘base.html’ %}
{% block blockname %}写相同的blockname即可覆盖
其他类比JavaWeb即可,思路是一样的
0 Comments