django_day3[静态文件配置,模板语言,基本数据库操作]
静态文件:
让django能把js等文件发给客户端用于渲染html。
#settings.py文件
STATIC_URL = '/static/' #这是django设置的别名
STATIC_ROOT=(
os.path.join(BASE_DIR,"sql/static") #这是自己设置拼接的 静态文件夹路径
)
#html中使用js css等文件的的使用方式
{% load staticfiles %} //在html文件第一行(整个文件的第一行)加上 load
<link rel="stylesheet" href="{% static 'dist/css/bootstrap.css' %}"> <script src="{% static 'dist/js/jquery-3.2.1.js' %}"></script> <script src="{% static 'dist/js/bootstrap.js' %}"></script>
模板语言(续)
###{{ 这里只能有一个参数 }}###
#views.py def temp(request): l=[11,22,33,44] d={"abc":11,"def":22} i=100 return render(request,"temp.html",{"l":l,"d":d,"i":i}) #html <body> <p>{{ i }}</p> <p>{{ l }}</p> <p>{{ d }}</p> </body> #页面渲染结果 100 [11, 22, 33, 44] {'abc': 11, 'def': 22}
深度查询:
深度查询 使用 句点号.
#示例 <p>{{ l.0 }}</p> <p>{{ l.1 }}</p> <p>{{ l.2 }}</p> <p>{{ l.3 }}</p> <p>{{ l.4 }}</p> //上面列表"l"的深度为四,这里取出了第五个数值由于不存在不会渲染出结果 #页面渲染结果 11 22 33 44
#字典类型示例 <p>{{ d.abc }}</p> <p>{{ d.def }}</p> #页面渲染结果 11 22
如果变量太多可以使用locals(),返回当前所有的变量
return render(request,"temp.html",locals())
循环
{% for book in book_list %}
<tr>
<th scope='row'>{{ book.id }}</th>
<td>{{ book.title }}</td>
<td>{{ book.price }}</td>
<td>{{ book.count }}</td>
<td>
<button class="btn btn-success">编辑</button>
<button class="btn btn-danger">删除</button>
</td>
</tr>
{% endfor %}
多分支判断
#i=20 {% if i > 50 %} <p>{{ i }}</p> {% elif i > 100 %} <p>i>100</p> {% else %} <p>i<50</p> {% endif %} #渲染结果 i<50
django配置数据库:
#settings.py 默认是sqlite3数据库 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } #app/models.py class Book(models.Model): #类名就是表名 格式:字段名=字段属性参数 title=models.CharField(max_length=32) price=models.IntegerField() count=models.IntegerField() #start command 数据库:库名为 appname_tablename python manage.py makemigrations //在app/migrations下生成 xxxx_initial.py文件 python manage.py migrate //写入表数据到数据库
注:字段属性参数 http://blog.csdn.net/devil_2009/article/details/41735611
浙公网安备 33010602011771号