python_oldboy17 Django

浏览器   urls:http://jd.com/caidian/
         urls.py:
		 1、 http://127.0.0.1:8000/timer    GET  无请求数据
		 2、 url:url(r'^timer/', views.showtime),
		 3、 views.py: showtime(request)
		 4、响应 时间字符串

		 一次请求响应结束后断开连接
		 request是所有请求信息的对象

		 1、http://127.0.0.1:8000/login/    GET   无请求数据
		 2、url(r'^login/', views.login),
		 3、views.py: login(request)
		 4、响应 :login.html

		 1、http://127.0.0.1:8000/valide/   POST   {"user":"yuan","pwd":"123"}
		 2、url(r'^valide/', views.valide),
		 3、views:valide(request)
		 4、if 成功: 响应字符串,验证成功

		 注:<form>表单中action="/validate/"也可以
Terminal: python manage.py runserver 127.0.0.1 8090

详见Django项目MTV  应用app01
Terminal:   python manage.py startapp blog
urls:   ^blog/article/d+/,article  ^blog/article/d+/$,article
views:  def article(request)
urls:   ^blog/article/(d+)/,article
views:  def article(request,id) 将d+数字作为参数传过来
正则表达式中分组的概念
无名分组:
urls:   ^blog/article/(d+)/(d+)/,article
views:  def article(request,year,month) 将d+数字作为参数传过来
    return HttpResponse("OK"+year+month)
有名分组,关键字传参:
urls:   ^blog/article/(?p<year_id>d+)/(?p<year_id>d+)/,article
views:  def article(request,year_id,month_id) 将d+数字作为参数传过来
    return HttpResponse("OK"+year_id+month_id)
url有先来后到顺序,先匹配到的会覆盖后匹配到的。
解耦;总的urls做分发应用:
路由分发app:import include
    urls:^blog/,include('blog.urls')
    models新建urls.py:^article/(d+)/$,article
POST请求 settings中 MIDDing 注释掉第四行
url改名字:涉及到url的都需要改,维护代价较大
硬编码/生写
解决:反向解析     render方向反向解析urls,再发送前端
urls:^login,app01.login,name="LOGIN"
views:<form action="{% url'LOGIN' %}" method="post">
视图部分:
url系统:url的路径与视图函数的映射关系
视图函数:requests 请求对象 属性:request.POST post请求数据组字典{}
    request.method 请求方法字符串str
    request.GET get请求数据字典{}
    request.path 当次请求的路径
    request.COOKIES
    get方法:get_full_path() 全路径
    pycharm console可查看print信息
多选 getlist():login.html
<p>爱好<inpput type="checkbox" name="hobby" value="1">篮球
<p>爱好<inpput type="checkbox" name="hobby" value="2">足球
<p>爱好<inpput type="checkbox" name="hobby" value="3">皮球
hobby=request.POST.get("hobby") print("hobby":hobby)    只能拿到一个爱好
hobby=request.POST.getlist("hobby") print("hobby":hobby)    拿到所有的爱好
response(响应对象):HttpResponse() render() redirect()
    render()方法  render(request,template_name,context)
template_name模板
context上下文
urls:index/,index,name="INDEX"
vies:def index(request):s="yuan" db中取出的信息   return render(request,"index.html"),{"name":s}
template:index.html <h1>hello {{ name }}
拼路径 from MTV import settings
def index(request):import s;path=os.path.join(setting.BASE_DIR,"templates","index.html")
    with open(path) as f:f.read()
    data=data%s return HttpResponse(data)
redirect()本身是渲染 跳转 重定向
redirect("/login/");redirect("/路径/")
模拟点击
redirect与render的区别:redirect两次请求,render一次请求

template模板层:
    功能:为了更有逻辑的将数据库中的数据渲染到模板中。
    模板语法:变量 {{  }}
    标量{%  %}
深度查询 句点符.
{{ date }}默认对象的格式
{{ date.year }} 只获取其中年的信息
{{ date.month }}
person_list=[alex,egon,yuan]
{{ person_list }}   只是拿到了对象属性
{% for person_obj in  %}
{{ person_obj.dream }}
{% endfor %}    方法中不能有参数
变量中的过滤器:{{ var|filter_name:参数 }}
{{ age|add:10 }}    在age=12的基础上再加10为22
{{ date|date:"Y-m-d" }}
{{ l|default:"nothing" }}   默认值
{{ l|length }}  长度
{{ 123123123|filesizeformat }}
{{ "hello world"|slice:"2:-1" }}    顾头不顾尾 -1为最后面的值
{{ "hellowoorld"|truncatewords="3" }}   按单词截
{{ "hellowoorld"|truncatechars="3" }}   按字符数量截
def index(request):render(request,"index.html",locals())    locals直接接收变量渲染到页面
index.html:{{ a_ele }}作为文本渲染出来了,而不是标签
    安全机制原因,避免xml攻击或恶意攻击
    评论内容:<script> for(1000) alert(123)
    {{ a_ele|safe }}  标签会渲染出来

models模型层  表格增删改
新建Django项目bookManager 应用booklist
urls:
    url(r'^index/', views.index),
    url(r'^add/', views.add),
    url(r'^del/(d+)', views.delete),
    url(r'^edit/(d+)', views.edit),
views:
def index(request):
    # 查询所有的0书籍
    bookList=models.Book.objects.all();
    return render(request,"booList/index.html",{"bookList":bookList})
def add(request):
    if request.method == "POST":
        title=request.POST.get("title");
        pubDate=request.POST.get("pubDate");
        price=request.POST.get("price");
        publish=request.POST.get("publish");
        models.Book.objects.create(title=title,pubDate=pubDate,price=price,publish=publish);
        return redirect("/index/");
    return render(request,"booList/add.html");
def delete(request,id):
    models.Book.objects.filter(id=id).delete();
    return redirect("/index/");
def edit(request,id):
    if request.method == "POST":
        title=request.POST.get("title");
        pubDate=request.POST.get("pubDate");
        price=request.POST.get("price");
        publish=request.POST.get("publish");
        models.Book.objects.update(title=title,pubDate=pubDate,price=price,publish=publish);
        return redirect("/index/");
    edit_bookList=models.Book.objects.filter(id=id)[0];
    return render(request,"booList/edit.html",{"edit_bookList":edit_bookList});

templates: index.html add.html edit.html
models.py:
class Book(models.Model):
    id=models.AutoField(primary_key=True)
    title=models.CharField(max_length=32)
    pubDate=models.DateField()
    price=models.DecimalField(max_digits=6,decimal_places=2)
    publish=models.CharField(max_length=32)

  <link rel="stylesheet" href="/static/dist/css/bootstrap.css">
bookManage项目下新建package statics 复制bootstrap包中的dist到statics下
  settings中的:
  STATIC_URL = '/static/'
STATICFILES_DIRS=[
    os.path.join(BASE_DIR,"static")
]
models.py
ORM ->model:pymysql模块 cursor.execute("select * from book")对象.方法->mysql->sql->db
ORM class Book:id,title... 类与对象的操作对应到sql操作
ORM坏处:慢
ORM好处:对数据库迁移特别方便
ORM映射:表记录-------类实例对象
表名----------类名
字段----------属性
models.py:
class Book(models.Model): 首字母大写
id=models.AutoField(primary_key=True) 自增约束1、数字类型,2、index索引
title=models.CharField(max_length=32)
pubDate=models.DateField()
price=models.DecimalField(max_digits=6,decimal_places=2) 总位数6位,小数点2位。
publish=models.CharField(max_length=32) decimal比double与float精度要高
settings DATABASE= sqlite3改成mysql 暂时使用sqlite3
Terminal:pytohn manage.py makemigratinos 应用bookList中生成了migrations下的py文件
Terminal:pytohn manage.py migrate 有db.sqlite3文件
打开database,将db.sqlite3拖入查看 只看bookList_book
确认settings中INSTALLed-APPs中是否有应用bookList
navicat图形化界面管理mysql
点击+号,输入字段信息 刷新保存
原文地址:https://www.cnblogs.com/liweijing/p/7809595.html