简体   繁体   中英

Django: TypeError at /1/ context must be a dict rather than QuerySet

this is my first Post on this Site. I am learning Django and Python right now and trying to create a Quiztool. I have hughe problems with creating my views and its hard for me to understand how to refine the data in a Queryset. In my Detail View I am raising this error:

TypeError at /1/

context must be a dict rather than QuerySet.

Request Method: GET Request URL: http://192.168.188.146:8080/1/ Django Version: 2.0.1 Exception Type: TypeError Exception Value:

context must be a dict rather than QuerySet.

Exception Location: /home/flo/Django2.0/lib/python3.5/site-packages/django/template/context.py in make_context, line 274 Python Executable: /home/flo/Django2.0/bin/python Python Version: 3.5.3 Python Path:

['/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']

Server time: Thu, 1 Mar 2018 11:00:35 +0000

I know I have to put the Queryset into a Dictonary but i dont know how to do this.

Here is my 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)

And here the detail.html:

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

If u need further informations to help me just ask.

Many thanks in advance and my Regards flotzen

You're returning question rather then the dic question_dict in here:

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

it should be

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

将您需要的所有内容放入“ question_dict”字典中的模板中,然后通过如下所示的渲染:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM