Django学习(三)- 模板渲染

1. 路由设置补充

首先我们补充一点上一节中关于url那一块的内容

    我们知道了其中的一些必要参数,这里我们来实际操作一下试试看
    首先,我们再添加几个其他的视图函数,在通过url进行映射

polls/views.py

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

polls/urls.py

from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

    大家会注意到这里的<>,我们可以在里面定义类型,后面跟一个参数关键字,在我们去访问的时候,表达的含义就是url后面跟随的该类型的关键字,并且该参数会自动传递给这里你设置的视图函数,比如第一个我们访问/polls/34/会调用views里面的detail方法,并且将这里传递的int型数字34传给detail方法作为参数,方法会在页面中返回你的数字,其他方法也是一致的,当你传递对应类型的参数时,调用对应方法,并返回该参数。

  • 这里的尖括号“捕获”URL的一部分,并将其作为关键字参数发送到视图函数

2. 数据查询

    我们在视图函数里面写相应逻辑时往往会需要模型里面的数据支持,这里就可以通过模型名字来获取里面的数据,语法:Moudle_name.object.method()
    一般就是模型名.object.对应方法(这里主要对数据进行过滤,比如:all()获取全部,filter()进行条件筛选,order_by()进行排序选择),例如:

from django.http import HttpResponse

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    output = ', '.join([q.question_text for q in latest_question_list])
    return HttpResponse(output)

# Leave the rest of the views (detail, results, vote) unchanged

3. 模板渲染

    当我们逻辑写好之后往往需要对页面的外观进行修改,这个时候我们就需要对html页面进行修饰并利用到views里面传递的数据
    这些html页面我们往往都放在一个叫templates的文件夹下,初使用时你可以直接在最外层目录下创建此目录,将一系列html文件丢进去,但是接触到后面我们是不推荐这样使用的,当你返回的模板html时,Django会去搜索所匹配的第一个栏目进行返回,当你的应用更多时往往会有同名模板出现,比如index.html等等,所以我们更推荐大家在每个应用中分别建立templates文件夹或者在最外层templates里面为每个应用独立出文件夹进行模板管理,在views里面返回时也只是需要在前面加上应用名即可,比如polls/index.html

i. 模板设置
    建立好相应文件之后,逻辑也处理完毕你会    发现去页面上访问仍然看不到效果,这是因为我们还没有对模板文件进行配置,Django还不知道去哪里寻找这些html文件,这里我之前的文章有提到,去这里
ii. 模板语言
    在html里面显然是无法直接调用python语法的,这里就需要模板语言,类似JavaWeb里面的语法,普通python语法都需要用{% %}包裹,然后里面加入对应的语法关键字,并且需要用相应的{% %}关闭,数值传递则用{{ }}包裹,如下:

<html>
<body>
#1. 循环
{% for x in xs%}
    <li><a href=" }}/">{{ x }}
{% endfor %}

#2. 选择
{%if x > 0 %}
    <li><a href=" }}/">{{ x }}
{% else %}
    <li><a href=" }}/">{{ x +1 }}
{% endif %}


</body>

</html>

我们在案例中进行演示

polls/templates/polls/index.html

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

更新视图函数

polls/views.py

from django.http import HttpResponse
from django.template import loader

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))

iii. 模板返回
    这里我们可以通过更加便捷的方法来返回我们的模板文件,就是前文提到过的render方法

from django.shortcuts import render

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)
  • 视图函数里面传递的字典参数(context)会一同传递到html文件当中,所以我们可以直接使用,这里注意传递的参数名字即可

iv. 错误页面设置
    我们也可以自行定义访问出错时候的页面处理,Django有对应的方法对异常进行捕获,我们在对应的html页面里面对参数进行展示即可

from django.http import Http404
from django.shortcuts import render

from .models import Question
# ...
def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})

4. 常见方法示例

i. get_object_or_404()

    这是一个常见的习惯性用法,该get_object_or_404()函数将Django模型作为其第一个参数和任意数量的关键字参数,并将其传递给get()模型管理器的函数。如果对象不存在则引发Http404

from django.shortcuts import get_object_or_404, render

from .models import Question
# ...
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

ii. 属性查找
    我们在views将上下文变量(context字典参数)传递给页面过后,该参数作为一个对象,页面可以通过“.”调用它的值或者内部方法

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

iii. 取消页面硬编码
    当我们通过后台对页面进行渲染时,往往涉及的是动态数据,所以在一些url或者链接构造上就不需要硬性编写清楚了,可以通过上面提到的上下文参数动态获取

<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

    其实这里也是涉及到了硬性编码,在大型项目中如果我们对文件夹或者url进行了修改,这里也是需要大量改动的,所以这里就衍生出了Django里面特殊的url定义,还记得之前设置urls.py里面给视图函数设置的别名name么,这里就用的上了,按照{% url name parms%}的格式传递即可

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

iv. 命名空间

    这里我们只有一个应用程序polls。在真正的Django项目中,可能有五个,十个,二十个应用程序或更多。Django如何区分它们之间的URL名称?如何使Django知道在使用模板标签时为url创建哪个应用视图 ?{% url %}

    答案是为URLconf添加名称空间。在polls/urls.py 文件中,继续并添加一个app_name以设置应用程序命名空间,在html里面调用时只需要在url后面也先跟上这个命名空间再写出对应的命名即可:

polls/urls.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

猜你喜欢

转载自blog.csdn.net/weixin_34345753/article/details/87230588