django 基础(二)

一:url是一个正则拼接

    

二:回复

  【回复也要按照人家的规则来回复】

    先引入模块  【 from django.shortcuts import HttpResponse 】

    回复格式 【 return HttpResponse("回复内容")】

三:函数

    调用函数的时候 括号里面必须又  【 request 】 原因不详

    【def index(request)】

 

四:render 【渲染】

    引入 【 from django.shortcuts import render 】

    写法 【 return render(request,"index.html") 】 

    注: 只这样写不对,因为找不到文件  

五:配置文件

  找到 【 settings.py 】 文件

  第五十四行找到  【 TEMPLATES /模板 】 然后五十七行 找到  【 “DIRS”  /目录】 意思事找到我模板的目录 设置路径

   首先看    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   【最括号里面的意思事当前路径的绝对位置】

                                         【前面上一层/再前面再上一成】  

           “DIRS”:[os.path.join(BASE_DIR,templates【文件夹名字】)]

六:链接数据库

    在html文件里面的  <tobdy></tbody>里写

      {% for i in userinfo_list %}<tr><td>{{i.id}}</td><td>{{i.user}}</td><td>{{i.password}}</td></tr>{% endfor %}

代码如下

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>主页</title>
</head>
<body>
<table border="1">
    <thead>
    <tr>
        <th>#</th>
        <th>数字</th>
        <th>字母</th>
    </tr>
    </thead>
    <tbody>
    {% for i in userinfo_list %}
        <tr>
            <td>{{i.id}}</td>
            <td>{{i.user}}</td>
            <td>{{i.password}}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>
</body>
</html>
 1 def index(request):
 2     # request就代表了请求的所有内容
 3     # return HttpResponse("ok")
 4     import pymysql
 5     conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="666", db="day1")
 6     cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
 7     cursor.execute("select id,user,password from userinfo")
 8     userinfo_list = cursor.fetchall()
 9     cursor.close()
10     conn.close()
11     return render(request,"index.html",{"userinfo_list":userinfo_list})

 

      

 

posted @ 2017-11-26 14:28  敌说  阅读(31)  评论(0)    收藏  举报