/ polls / context中的TypeError必须是dict而不是RequestContext

时间:2017-12-20 07:51:24

标签: python django pycharm

这是django中我的民意调查应用的view.py标签。我无法调试错误:Type Error: context must be a dict rather than RequestContext.它取自我的第一个django应用程序的YouTube集合的第6个视频'来自渠道' The Codex'。请帮帮忙?

from django.shortcuts import render

from django.http import HttpResponse
from django.template import loader, RequestContext
from .models import Question

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

def detail(request, question_id):
    return HttpResponse("This is the detail view of the question: %s" %question_id)

def results(request, question_id):
    return HttpResponse("These are the results of the question: %s" %question_id)

def vote(request, question_id):
    return HttpResponse("Vote on question: %s" %question_id)

3 个答案:

答案 0 :(得分:0)

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

但是

def index(request):
    latest_questions = Question.objects.order_by('-pub_date')[:5]
    return render(request, 'polls/index.html', {
            ''latest_questions': latest_questions
        })

好多了。

该视频的使用情况很旧,如果您是新手,我建议您直接学习Django1.11.django 1.11的Doc是here

答案 1 :(得分:0)

我正在使用相同的教程系列并遇到同样的问题。 而不是像这样使用RequestContext

 context = RequestContext(request,{
    'latest_questions': latest_questions
})

使用此词典

context = {
    'latest_questions': latest_questions,
}

我从Django文档中得到了这个。

答案 2 :(得分:-1)

试试这个而不是你的。

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