python - Django 模板和 render() - 如何访问多个值

标签 python django django-templates django-views

学习 Django 时我遇到了访问 2 个不同值的问题。

def home(request 下的 views.py 中,我添加了一个包含 2 个字典对象的列表,并在 context 下传递它. 它工作得很好,我正准备在我的 front_page.html 模板中循环遍历字典,但我还添加了一个简单的 if title 变量,它只能工作如果我将 {'title': 'Competitive'} 放在变量 context 之前。

 from django.shortcuts import render


# Create your views here.

owl = [
    {
        'title': 'Competitive'
    },
    {
        'Team': 'Dynasty',
        'Location': 'Souel Korea',
        'Colors': 'Black & Gold',
    },
    {
        'Team': 'OutLaws',
        'Location': 'Houston',
        'Colors': 'Green & Black',
    }
]


def home(request):
    context = {
        "owl": owl
    }

    return render(request, 'overwatch_main_app/front_page.html', context, {'title': 'Competitive'})


def second(request):
    return render(request, 'overwatch_main_app/about.html', {'title': 'Boom'})

我什至尝试过 comp = {'title': 'Competitive'},并将 comp 放入 render()。它仅在我将 comp{'title': 'Competitive'} 放在 content 之前,然后是 content 时才有效> 不起作用。

return render(request, 'overwatch_main_app/front_page.html', comp, context)

return render(request, 'overwatch_main_app/front_page.html', {'title': Competitive'} , context)

如何通过 render() 将超过 1 个字典值传递到我的模板

front_page.html

{% extends 'overwatch_main_app/base.html'  %}

{% block content %}

    <h1> OverWatch</h1>

    {% for o in owl %}

        <p>{{o.Team}}</p>
        <p>{{o.Location}}</p>
        <p>{{o.Colors}}</p>

    {% endfor %}

{% endblock %}

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    {% if title %}
        <title>OverWatch {{title}}</title>
    {% else %}
        <title> OverWatch </title>
    {% endif %}

</head>
<body>

    {% block content %}{% endblock %}

</body>
</html>

最佳答案

你只能有一个上下文字典,但字典可以有任意多的键/值。

context = {
    "owl": owl,
    "title": "Competitive"
 }
return render(request, 'overwatch_main_app/front_page.html', context)

关于python - Django 模板和 render() - 如何访问多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53448869/

相关文章:

python - 在 Tastypie 中获取请求参数

django - Django 的模板语言不会在异常时静默失败?

python - 在 Django 中不属于您网站的抽象网址

django - other_dict 必须是一个映射(类字典)对象

python - 模块 'darknet' 没有属性 'load_network'

python - GEvent PyWSGI SSL 非常慢

python - 与 pygame 中的归一化向量移动不一致?

python - 为什么我从 pandas/matplotlib 收到错误 "OverflowError: Python int too large to convert to C long"?

javascript - 如何通过 Django Channels 实现视频通话?

python - Django:将 gmt 时间而不是本地时间存储在数据库表中