【问题标题】:Django: TypeError at /1/ context must be a dict rather than QuerySetDjango:/1/ 上下文中的 TypeError 必须是 dict 而不是 QuerySet
【发布时间】:2018-03-01 11:15:23
【问题描述】:

这是我在这个网站上的第一篇文章。我现在正在学习 Django 和 Python,并尝试创建一个 Quiztool。我在创建视图时遇到了巨大的问题,而且我很难理解如何优化查询集中的数据。在我的详细视图中,我提出了这个错误:

/1/ 处的类型错误

context 必须是 dict 而不是 QuerySet。

请求方法:GET 请求地址:http://192.168.188.146:8080/1/ Django 版本:2.0.1 异常类型:TypeError 异常值:

context 必须是 dict 而不是 QuerySet。

异常位置: /home/flo/Django2.0/lib/python3.5/site-packages/django/template/context.py 在 make_context 中,第 274 行 Python 可执行文件: /home/flo/Django2.0/bin/python Python版本:3.5.3 Python路径:

['/home/flo/Django2.0/quiztool', '/home/flo/Django2.0/lib/python35.zip', '/home/flo/Django2.0/lib/python3.5', '/home/flo/Django2.0/lib/python3.5/plat-x86_64-linux-gnu', '/home/flo/Django2.0/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/home/flo/Django2.0/lib/python3.5/site-packages']

服务器时间:2018年3月1日星期四11:00:35 +0000

我知道我必须将查询集放入字典中,但我不知道该怎么做。

这是我的views.py:

def index(request):
    latest_survey_list = Survey.objects.order_by('survey_id')[:5]

    context = {
        'latest_survey_list': latest_survey_list
    }
    return render(request, 'fragen/index.html', context)

def detail(request, survey_id):

    question = Survey.objects.get(pk=survey_id).question.all().values()
    question_dict = {
        'question': question
    }

    return render(request, 'fragen/detail.html', question)

这里是detail.html:

{% if question %}
    <ul>
    {% for x in question %}
    <li>{{ x.question_text }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No questions are available.</p>
{% endif %} 

如果您需要更多信息来帮助我,请询问。

非常感谢提前和我的 问候flotzen

【问题讨论】:

    标签: python django django-queryset


    【解决方案1】:

    您返回的是 question,而不是这里的 dic question_dict

    return render(request, 'fragen/detail.html', question)
    

    应该是

    return render(request, 'fragen/detail.html', question_dict)
    

    【讨论】:

    • 哇,这真的是一个简单的解决方案......现在我觉得自己很愚蠢......非常感谢=)
    • 没问题,我们有时会忽略最简单的事情:)
    【解决方案2】:

    将您需要在模板中的所有内容放入“question_dict”字典中 然后像这样通过渲染:

    return render(request, 'fragen/detail.html', context=question_dict)
    

    【讨论】:

      猜你喜欢
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多