day2 django基础 2

    xiaoxiao2021-04-15  197

    day2 django基础 2

    复习

    django-admin startproject python manage.py startapp settings.py 配置 文件 主 urls.py 路由在这个文件中配置 视图的参数 request对象 HttpResponse urlpatterns = [ path() ] 1.url添加参数: 视图中get 获取 http://127.0.0.1:9000/detail/ 2.url添加参数:试图函数中 也传参 这两个的参数名必须一致 3.http://127.0.0.1:8000/<p_id>/ book urls.py 项目名 settings urls wsgi manage.py from django.urls import path,include urlpatterns = [ path(r'',include("book.urls")) ] path函数 url re_path() ?P<参数名>[0-9]{4}

    自定义url 转化器

    系统提供的转化器 有 int str uuid path 等

    path(r’//int:book_id’,) 有个需求是这样的

    1.获取python分类下面的文章 /articles/python 2.获取python和django 分类下的文章 /articles/python+django 这是url中的表现形式 ['python',django] //视图函数处理的时候 需要的是 列表这种形式 3.获取python 和 django 和flask 下的文章 /articles/python+django+flask/ 以此类推 url中 文章分类的参数传递到视图函数之前 应该把它分开存储到列表中 python+django ['python',django] reverse 反转 将列表变成 python+django

    【步骤】:

    需要定义一个类 继承于object即可在类中需要定义一个属性 限制规则的正则表达式 path(r’/book/kangbazi:book_id’)创建to_python方法 将url中的值转化成列表 传给视图函数 python+django =》 [‘python’,django]创建to_url方法 [‘python’,django] =》 python+django将创建好的转化器注册到django中在应用的 __init__文件中 要引入 引入转化器所在的文件 1.http://127.0.0.1:8008/article/list/python+flask+django+tornado+tomcat/ 在浏览器中输入 2.通过转化器 给你转化成了列表 转化后的列表是:['python', 'flask', 'django', 'tornado', 'tomcat'] 3.将列表 通过 url_name 进行反转 得到 /article/list/python+flask+django+tornado+tomcat/

    渲染模板

    HttpResponse() 参数为字符串

    render_to_string() 将模板编译成 python的字符串格式 再通过HttpResponse返回给页面render() rom django.http import HttpResponse from django.shortcuts import render #这是渲染模板用的 from django.template.loader import render_to_string # Create your views here. def index(request): # html = render_to_string('index.html') # return HttpResponse(html) return render(request,'index.html')

    模板是如何进行渲染的

    settings.py 1.TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], #渲染模板的时候会在这个路径下面进行查找 'APP_DIRS': True, 如果这个为True 会到INSTALLED_APPS 已经注册的app下面的templates 模板中进行查找 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] 2.render('index.html') 先查 DIRS有就返回 没有 的话 检查 这个视图所在的app 是否在 会到INSTALLED_APPS 已经注册 那么就到app下面 的template下面查找 如果没有 就到其它已经注册的app下面的 templates 下面查找

    模板变量

    from django.shortcuts import render class Person(object): def __init__(self,username): self.username = username def index(request): p = Person("jiangjiejie") context = { # 'person':{ # 'username':p.username # } # 'person':( # '红楼梦', # '西红柿首富', # '金什么梅', # '水浒传' # ) } return render(request,'index.html',context=context) html {{ person.username }} {{ person.2 }}

    模板中常用的标签

    所有的标签 都在 {%%}中 注释 {# #} if 有闭合标签 {% endif %} if 是可以进行判断的 跟python一样 == != < <= > >= in not in is is not {# 在模板中使用变量 四个大括号 {{ person.2 }}#} {# {% if age < 18 %}#} {# <p>您是未成年人,不能上车</p>#} {##} {# {% elif age == 18 %}#} {# <p>您是成年人,可以上车</p>#} {# {% else %}#} {# <p>樯橹灰飞烟灭</p>#} {# {% endif %}#} {##} {# {% if '91wangfan' in heros %}#} {# <p><a href="http://www.91.com">wanfan的种子</a></p>#} {# {% else %}#} {# <p> 欠91wangfan一个vip 奥斯卡欠他一个最佳男主角</p>#} {# {% endif %}#}

    for标签

    <table> <thead> <tr> <th>序号</th> <th>书名</th> <th>作者</th> <th>价格</th> </tr> </thead> <tbody> {% for book in books %} <tr> <td>{{ forloop.counter }}</td> <td>{{ book.name }}</td> <td>{{ book.author }}</td> <td>{{ book.price}}</td> </tr> {% endfor %} </tbody> </table>

    自定义过滤器

    在指定的应用中创建 templatetags python包 名字必须为 templatetags 否则找不到在templatetags 创建一个py 文件 用来存储过滤器写完以后我们要注册到django.template.Library.filter过滤器所在的app 记得注册到 settings.INSTALLED_APPS在模板中还得加载 这个过滤器 article app templatetags python包 myfilter.py from datetime import datetime from django import template register = template.Library() @register.filter('my_greet') def greet(value,word): return value+word @register.filter def time_since(value): """ 1分钟以内 刚刚 1小时以内 几分钟之前 一天以内 几小时之前 30天以内 几天之前 具体的时间 """ if not isinstance(value,datetime): return value now = datetime.now() timestamp = (now-value).total_seconds() if timestamp < 60: return '刚刚' elif timestamp >= 60 and timestamp < 60*60: minutes = int(timestamp/60) return "%s分钟前" % minutes elif timestamp >= 60*60 and timestamp < 60*60*24: hours = int(timestamp/60/60) return "%s小时前" % hours elif timestamp >= 60*60*24 and timestamp < 60*60*24*30: days = int(timestamp/60/60/24) return "%s天前" % days else: return value.strftime("%Y/%m/%d %H:%M:%S") article app views.py from django.shortcuts import render from datetime import datetime # Create your views here. def index(request): context = { "value":"kangbazi", "mytime":datetime(year=2019,month=5,day=21,hour=10,minute=25,second=6) } return render(request,'myfilter.html',context=context) templates myfilter.html {% load my_filter %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>自定义过滤器</title> </head> <body> {{ value|my_greet:"helloboy" }} {{ mytime|time_since }} </body> </html>

    最新回复(0)