美文网首页
第四节、URL及模版基础

第四节、URL及模版基础

作者: 妄语莫言 | 来源:发表于2018-02-22 16:14 被阅读0次
URL配置文件查看源码
def url(regex, view, kwargs=None, name=None):
    return re_path(regex, view, kwargs, name)

默认接受4个参数

  • regex代表正则匹配的字符
  • view代表视图文件views.py中对应调用的函数方法
  • kwargs接收的是不定长参数,默认值是None,一般接收字典**args
示例:
url文件发送参数
url(r'^books/', include('books.urls'),{'seitch':'true'}),
views文件里面接收参数
def index(request,**args):
    if  arg.get('switch') == 'true':
           print(datetime.datetime.now())
     return HttpResponse('<h1>这是首页</h1>')
#**args接收url文件中传过来的字典
# arg.get('switch') 根据字典的键key取得对应的值然后进行对应的操作如这里的打印系统时间操作会在服务器的后台显示相应的信息,类似一个开关的作用
  • name给一个匹配的url地址取名字,类似泣别名的作用,一般用于模板,也可以使用reverse进行页面重定向
url文件
url(r'^article/$', views.article,name='books_article'),
url(r'^article_new/$', views.article_new,name='books_article_new'),
#给自己所在这行url起别名books_article
views文件里面可以放新旧两个函数
def article(request,**kwargs):
    return HttpResponse('这是旧文章首页')
def article_new(request,**kwargs):
    return HttpResponse('这是新文章首页')
原本是两个url和两个函数一一对应,而且字典{'seitch':'true'}在主url文件里直接传入,这样book的url中就不用添加字典了23
修改视图函数
from django.shortcuts import render,reverse
from django.http import HttpResponse,HttpResponseRedirect
def article(request,**kwargs):
    if kwargs.get('switch') == 'true':
        return HttpResponseRedirect(reverse('books_article_new'))
    return HttpResponse('这是旧文章首页')
达到的效果就是访问旧url时直接跳转到新页面

通过给url取名字,以后在view或者模板中使用这个URL,就只需要通过这个名字就可以了。这样做的原因是防止url的规则更改,会导致其他地方用了这个url的地方都需要更改,但是如果取名字了,就不要做任何改动了。

模版基础

我们刚开始是原始的直接将html字符串硬编码HttpResponse中。
使用template和Context动态修改html中的内容来构建

#第一种
from django.template import Template,Context
def index_1(request,bn):
    # 生成模板
    t = Template('这是首页,欢迎浏览{{books_name}}')
    # 生成上下文
    c = Context({'books_name':bn})
    # 渲染
    html = t.render(c)
    # 响应返回值
    return HttpResponse(html)
#第二种
from django.template.loader import get_template
def index_2(request,bn):
#从app目录获取模版
    t = get_template('books/index.html')
#传值渲染
    html = t.render({'books_name':bn})
#返回值响应
    return HttpResponse(html)
#第三种为了减少加载模板、渲染模板等重复工作,django提供了处理这些工作的快捷函数render_to_string(template_name, context=None, request=None,using=None)
from django.template.loader import render_to_string
def index_3(request,bn):
    html = render_to_string('books/index.html',{'books_name':bn})
    return HttpResponse(html)
#第四种使用render_to_response进行渲染,不需要HttpResponse。
from django.shortcuts import render_to_response
def index_4(request,bn):
    return render_to_response('books/index.html',
                              {'books_name': bn})

使用render进行渲染

# 第五种
from django.shortcuts import render
def index_5(request,bn):
    return render(request,'books/index.html',
                              {'books_name': bn})

一般在app的目录下新建模版目录templates,该目录下再放一个app同名的目录,将模版文件,放在包含模版的目录的templates子目录下。 将setting文件中INSTALLED_APPS 这个列表中添加对应的app名字基本思路是,使得每个APP的的模版子目录下都有一个子目录来唯一对应这个APP。
当APP_DIRS值为True,则模板会去安装了的app下面的templates文件夹查找模板。

  • 我们之前创建了books的app,将这个app添加到setting.py文件的INSTALLED_APPS列表中
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'books',
]
#APP DIRS对应值为True会自动去app目录下的templates下查找对应的模版文件
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
  • 模版文件中调用变量
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
这是读书的首页,欢迎{{ books_name }}
</body>
</html>
总结参数传递的过程

就是将url中的参数传递给视图函数views进行渲染得到结果

  • 浏览器访问url:http://127.0.0.1:8000/books/hi/c/
  • 主url指向app的url文件 url(r'^books/', include('books.urls')),
  • app的url 处理获取参数url(r'^hi/(\w+)/$', views.index_5),传递给视图函数里的index_5,这里获取c
  • views视图里面的index_5
    def index_5(request,bn)
    return render(request,'books/index.html',{'books_name': bn}
    用参数bn获取上面传递的内容c,然后通过字典复制给变量books_name,同时去对应的app的模版目录下调用模版渲染结果后返回
模版变量

查看源码redener的参数如下
def render(request, template_name, context=None, content_type=None, status=None, using=None):
方法五

def index_5(request,bn):
    return render(request,'books/index.html',
                           context= {'books_name': bn})

context后面是一个字典key-value键值对的形式
字典的值可以是字符串、字典、列表、类、实例化的类以及函数等
例子中的bn就是字符串,模版文件中直接使用{{key_name}}的形式调用键获取对应的值

    这个变量是字符串对象:{{ books_name}}<br>
    这个变量是函数对象:{{ hello}}<br>
    这个变量是类方法对象:{{ fruits_say}}<br>
    这个变量是类对象:{{ fruits}}<br>
    这个变量是类对象,访问类对象的属性:{{ fruits.name}}<br>
    这个变量是类对象,访问类对象的方法:{{ fruits.say}}<br>
    这个变量是列表对象{{ list }}<br>
    这个变量是列表对象,访问列表的元素{{ list.1 }}<br>
    这个变量是字典对象{{ dict }}<br>
    这个变量是字典对象,访问字典的键{{ dict.a }}<br>
# books/views.py
def hello():
    return 'django'

class Fruits:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    def say(self):
        return 'HAHAHAHA'  
    
ap = Fruits('apple','red')
ls = ['x','y','z']
dc =  {'a':1,'b':2}
from django.shortcuts import render
def index_5(request,bn):
    return render(request,'books/index.html',
                  context={'books_name':'python',#字符串
                           'hello':hello,        # 函数
                           'fruits_say':ap.say,  # 方法
                           'fruits':ap,          # 类对象
                           'list':ls,            # 列表
                           'dict':dc,            # 字典
                           }) 

相关文章

网友评论

      本文标题:第四节、URL及模版基础

      本文链接:https://www.haomeiwen.com/subject/kauttftx.html