3. 视图和模板

441 阅读2分钟

MVT模型中,V指的是views,T指的是template。通过我们前面讲的urls找对应的viewview再处理request中的数据,然后封装成成dict参数,传递到视图中展示出来就可以了。

我们通过返回值render查找到模板。

首先通过settings中设置的TEMPLATES参数DIRS中加载模板。 如果TEMPLATES中参数APP_DIRS设置为True的话,回到当前view对应的app中的templates文件夹中查找模板。还没有就到其他app中查找模板,都没有就抛出TemplateDoesNotExist异常。

视图

再django中默认模板有django template(直接就能使用),现在用得比较多的mako模板(需要下载mako模块)。这里只讲django template默认模板中的3种返回的类型。这是比较常用的大概80%情况都是这些。

HttpResponse

返回一个字符串,如果这个字符串是html代码的话可以被识别出来。

from django.shortcuts import HttpResponse
def book(request):
    text = "<h1>Success</h1>"
    return HttpResponse(text)

render

渲染一个模板,并可以带参数渲染,通过模板的渲染就可以展示传递的参数。

from django.shortcuts import rennder
def book(request):
    data = {"who":"huixiong"}
return render(request,"book_view.html",context=data)

JsonResponse

返回一个Json格式的字符串,需要传递一个dict类型的参数。

from django.shortcuts import JsonResponse
def book(request):
    data = {"who":"huixiong"}
return JsonResponse(data)

模板

通过render渲染的模板,并带有context参数,可以添加到模板的渲染拿结果中,常用的标签。

class a:
    __init__(self):
        self.show = "i am test"
def book(request):
    show = a()
    data = {
        "who":"huixiong",
        "family":["father","mom","sister"],
        "grade":{
            "math":1,
            "chinese":2,
            "english":3
        },
        "test":show
    }
return JsonResponse(data)

获取参数

<p>{{who}}</p><!--这里打印 huixiong-->
<p>{{family.1}}</p><!--这里打印 mom-->
<p>{{grade.math}}</p><!--这里打印 2-->
<p>{{test.show}}</p><!--这里打印 test-->

if

{% if "math" in grade %}
<p>{{grade.math}}</p><!--这里打印 1-->
 {% else %}
 <p>没有数学成绩</p>
 {% endif %}
 
  {% for g in grade %}
     <p>{{ g }}</p><!--循环遍历字典grade输出value-->
 {% endfor %}
 
 {% for g in grade reversed %}
     <p>{{ g }}</p>
 {% endfor %}
<p>{{family.1}}</p><!--这里打印 mom-->
<p>{{grade.math}}</p><!--这里打印 2-->
<p>{{test.show}}</p><!--这里打印 test-->