模版之标签
模版里面使流程控制:if、else、else if、for
标签:{% tag %}
for 标签
后端代码
def tag(request): user_list = [1, 2, 3] return render(request, 'tag.html',locals())
前端代码
<body> {% for user in user_list %} {{ user }} {% endfor %} </body> </html>
结果
for循环中forloop属性
orloop.counter The current iteration of the loop (1-indexed) 当前循环的索引值(从1开始) forloop.counter0 The current iteration of the loop (0-indexed) 当前循环的索引值(从0开始) forloop.revcounter The number of iterations from the end of the loop (1-indexed) 当前循环的倒序索引值(从1开始) forloop.revcounter0 The number of iterations from the end of the loop (0-indexed) 当前循环的倒序索引值(从0开始) forloop.first True if this is the first time through the loop 当前循环是不是第一次循环(布尔值) forloop.last True if this is the last time through the loop 当前循环是不是最后一次循环(布尔值) forloop.parentloop 本层循环的外层循环
循环遍历字典
{% for key,val in dic.items %} <p>{{ key }}:{{ val }}</p> {% endfor %} {% for foo in d.keys %} <p>{{ foo }}</p> {% endfor %} {% for foo in d.values %} <p>{{ foo }}</p> {% endfor %}
for empty标签
循环遍历有值走for标签,没值走enpty标签
if标签
{% if num > 100 or num < 0 %} <p>无效</p> {% elif num > 80 and num < 100 %} <p>优秀</p> {% else %} <p>凑活吧</p> {% endif %}
if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。
with标签
前端代码
{% with d.hobby.3.info as nb %} <p>{{ nb }}</p> 在with语法内就可以通过as后面的别名快速的使用到前面非常复杂获取数据的方式 <p>{{ d.hobby.3.info }}</p> {% endwith %}
后端代码
def index(request): d = {'username':'kevin','age':18,'info':'这个人有点意思','hobby':[111,222,333,{'info':'NB'}]} return render(request,‘index.html’,locals)
ps:{% csrf_token %}加上这行标签就可以解决403的问题,可以不用再配置文件中注销中间件
模版继承(重要)
继承:继承之后的页面跟被继承的页面一模一样
继承需要用到:
{% extends '继承的html文件名' %}
继承之后如何修改:需要给继承html文件内容划分区域,但不会影响html的页面效果
如何划分:
{% block pag %}
需要修改的内容
{% endblock %}
案例
后端端代码
首页页面 def index(request): return render(request, 'index.html', locals()) 注册页面 def reg(request): return render(request, 'reg.html', locals()) 登录页面 def login(request): return render(request, 'login.html', locals())
前端代码
首页页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> {% block pag %} <title>首页页面</title> {% endblock %} </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li> <li><a href="#">Link</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> <li role="separator" class="divider"></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> <form class="navbar-form navbar-left"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Link</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <div class="container-fluid"> <div class="row"> <div class="col-md-3"> <div class="list-group"> <a href="#" class="list-group-item active"> 菜单栏 </a> <a href="/index/" class="list-group-item">首页</a> <a href="/login/" class="list-group-item">登录</a> <a href="/reg/" class="list-group-item">注册</a> <a href="#" class="list-group-item">更多</a> </div> </div> <div class="col-md-9"> <div class="panel panel-default"> <div class="panel-heading">精彩生活从这里开始!</div> <div class="panel-body"> {% block but %} 可以在被继承者中修改的内容 <div class="jumbotron"> <h1>欢迎来到我的世界</h1> <p>恶魔</p> <p><a class="btn btn-primary btn-lg" href="#" role="button">进入</a></p> </div> {% endblock %} </div> </div> <div class="row"> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="https://img1.baidu.com/it/u=4249132358,2043996728&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1691082000&t=11ebee95f67ff2c6c49ee772176a6d23" alt="..."> </a> </div> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="https://img1.baidu.com/it/u=4249132358,2043996728&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1691082000&t=11ebee95f67ff2c6c49ee772176a6d23" alt="..."> </a> </div> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="https://img1.baidu.com/it/u=4249132358,2043996728&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1691082000&t=11ebee95f67ff2c6c49ee772176a6d23" alt="..."> </a> </div> <div class="col-xs-6 col-md-3"> <a href="#" class="thumbnail"> <img src="https://img1.baidu.com/it/u=4249132358,2043996728&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1691082000&t=11ebee95f67ff2c6c49ee772176a6d23" alt="..."> </a> </div> </div> </div> </div> </div> </body> </html>
注册页面
{% extends 'index.html' %} 继承index页面 {% block pag %} 修改继承页面内容 <title>注册页面</title> {% endblock %} {% block but %} <from> <div class="form-group"> 用户名:<input type="text" value="" name="username" class="form-control"> </div> <div class="form-group"> 密码:<input type="password" value="" name="password" class="form-control"> </div> <div class="form-group"> <input type="submit" value="注册" name="register" class="form-control "> </div> </from> {% endblock %}
登录页面
{% extends 'index.html' %}继承index页面 {% block pag %} 修改继承页面内容 <title>登录页面</title> {% endblock %} {% block but %} <from> <div class="form-group"> 用户名:<input type="text" value="" name="username" class="form-control"> </div> <div class="form-group"> 密码:<input type="password" value="" name="password" class="form-control"> </div> <div class="form-group"> <input type="submit" value="登录" name="login" class="form-control"> </div> </from> {% endblock %}
模版的导入
{% include '需要导入的html文件' %} 需要在哪儿导入 直接写这段标签即可
模型层(modle.py)
常见的十几种查询方法
之前学过:filter all first update delete create
# 1.all() 查询所有数据 # 2.filter() 带有过滤条件的查询 # 3.get() 直接拿数据对象 但是条件不存在直接报错 # 4.first() 拿queryset里面第一个元素 # res = models.User.objects.all().first() # print(res) res = models.User.objects.all().last() print(res) # values value_list # select username,password from user # <QuerySet [{'username': 'kevin1', 'password': '123', 'age': 20}, # res = models.User.objects.values('username', 'password','age') # 指定查询的字段,返回的是列表套字典 # print(res) # <QuerySet [('kevin1', '123', 20), ('kevin2', '123', 20), ('kevin3', '123', 20), ('kevin4', '123', 20)]> # res = models.User.objects.values_list('username', 'password', 'age') # 指定查询的字段,返回的是列表套字典 # print(res) # 注意:返回的结果只有是QuerySet对象的时候,才有query属性,才能看sql语句 # print(res.query) # SELECT "app01_user"."username", "app01_user"."password", "app01_user"."age" FROM "app01_user" # res=models.User.objects.create() # 插入成功的这条记录对象 # print(res.query) # 第二种方式查看ORM的原生sql语句 # 去重, 每一条数据都要完全一样,如果说带主键,一定不会重复 # res = models.User.objects.all().values('password', 'age').distinct() # print(res) # 排序 # order by age asc/desc # res = models.User.objects.all().order_by('age') # 默认是升序排列 # res = models.User.objects.all().order_by('-age') # 降序排列 # res = models.User.objects.all().order_by('age', 'id') # 降序排列 # res = models.User.objects.all().order_by('age', '-id', '') # 降序排列 # print(res) # 反转,先排序,数据要先有序才能翻转 # res=models.User.objects.all().order_by('-age').reverse() # print(res) # git----->测试环境------>中文--------> # count # select count(*) from user # res = models.User.objects.count() # print(res) # exclude 排除 # res=models.User.objects.exclude(username='kevin1') # print(res) # exist # res = models.User.objects.filter(pk=20).first() # print(res)
查看原生代码
第一种:
res = models.UserInfo.objects.values('username', 'password',
print(res.query) # QuerySet对象,他都有一个属性query
增加、更新、删除没有queryset对象
第二种:直接在配置文件中加入下面的代码
LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level': 'DEBUG', }, } }
测试环境搭建
tests.py的用法
制作django环境
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'day58_dj.settings')
import django
django.setup() # 代码只能写在这句代码的下面
from app01 import models # 需要导入模块才能使用,运行直接右建运行
基于下滑线的查询
# 1 年龄大于35岁的数据 # select * from user where age > 10 # res = models.User.objects.filter(age__gt=10).all() # print(res) # 年龄小于10岁的数据 # res = models.User.objects.filter(age__lt=10).all() # print(res) # 年龄大于等于10岁的数据 e---------->equal # res = models.User.objects.filter(age__gte=10).all() # res = models.User.objects.filter(age__lte=10).all() # # 年龄是11 或者 20 或者 23 # select * from user where age in (11, 20, 23) # res = models.User.objects.filter(age__in=[11,20,23]).all() # print(res) # 年龄在18到40岁之间的 首尾都要 # select * from user where age between 18 and 40 # res = models.User.objects.filter(age__range=[11,40]) # print(res) # # 查询出名字里面含有s的数据 模糊查询 # select *from user where username like '%s%' # 回头复习 # res = models.User.objects.filter(username__contains='s').all() # print(res) # 用户名以s开头的 res = models.User.objects.filter(username__startswith='s').all() # res = models.User.objects.filter(username__endswith='s').all() print(res) # 查询出注册时间是 2023 5月 # select * from user where reg_time = '2023-05' # select date_format(reg_time, '%Y-%m') from user where date_format(reg_time, '%Y-%m') = '2023-05' # res= models.User.objects.filter(reg_time__month='5') # 查5月的 res= models.User.objects.filter(reg_time__month='5',reg_time__year='2023') # 查5月的 print(res)
外键字段查询
一对多的查询 # 图书和出版社是一对多的关系 增加一本图书? # 外键字段的查询和增加 # 增加一本图书 # models.Book.objects.create(title='洋哥自转', price=1000, publish_date='2023-08-01', publish_id=1) # publish_obj = models.Publish.objects.filter(pk=20).first() #查询不到会返回none值 try: publish_obj = models.Publish.objects.get(pk=20) # get查询不到 就报错,以后使用get查询try一下 except: pass # models.Book.objects.create(title='洋哥自转2', price=2000, publish_date='2023-08-02', publish=publish_obj) # print(publish_obj) # None # 删除一本图书 # models.Book.objects.filter(pk=1).delete() # 修改 # models.Book.objects.filter(pk=2).update(publish=publish_obj) # models.Book.objects.filter(pk=2).update(publish_id=3)
标签:下划线,modle,res,age,查询,models,objects,User,print From: https://www.cnblogs.com/shanghaipudong/p/17601526.html