TypeError:context必须是dict而不是HttpResponseRedirect

时间:2018-04-29 03:50:20

标签: django

我正在使用Django 2.0并尝试将用户重定向到get_context_data

中的其他视图

我的网址格式是

mainapp.urls

urlpatterns = [
    path('learn/', include('learn.urls', namespace='learn')),
    path('admin/', admin.site.urls),
]

app.url

app_name = 'learn'
urlpatterns = [
    path('success/<course_learn_id>/<session>', LearnSuccess.as_view(), name='success'),
]

LearnSuccess查看

class LearnQuestion(FormView):
    form_class = SessionForm
    template_name = 'learn/learn_question.html'

    def get_context_data(self, **kwargs):
        context = super(LearnQuestion, self).get_context_data(**kwargs)
        course_learn = CourseLearn.objects.get(pk=self.kwargs['course_learn_id'])

        session = self.request.GET['session']
        question, question_type, options, complete = CourseLearn.objects.get_next_question(course_learn, session)

        if complete:
            return redirect('learn:success', course_learn_id=course_learn.pk, session=session)

        context['complete'] = complete
        context['question'] = question
        context['question_type'] = context_type
        context['options'] = options
        context['session'] = session

        return context

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(self.__class__, self).dispatch(request, *args, **kwargs)

我使用Ajax呈现此视图,并希望在completeTrue时重定向用户

但这是错误的

TypeError: context must be a dict rather than HttpResponseRedirect.

我甚至试过return reverse(),但它也给出了错误。

尝试

return redirect('learn:success', kwargs={'course_learn_id':course_learn.pk, 'session':session})

给出错误

django.urls.exceptions.NoReverseMatch: Reverse for 'success' with keyword arguments 
'{'kwargs': {'course_learn_id': UUID('374ccfcd-37b5-40d3-8673-01ca111f42bc'), 'session': '1524972935'}}' not found. 
1 pattern(s) tried: ['learn\\/success\\/(?P<course_learn_id>[^/]+)\\/(?P<session>[^/]+)$']

2 个答案:

答案 0 :(得分:2)

get_context_data()应该是为了在渲染之前向模板添加其他上下文。执行其他视图级逻辑

您正尝试从那里返回重定向响应对象,该对象无效 - get_context_data()的返回值只能是字典。

您当前尝试在此处执行的逻辑应改为您的get()方法,例如:

def get(self, *args, **kwargs):
    course_learn = CourseLearn.objects.get(pk=kwargs['course_learn_id'])
    session = self.request.GET['session']
    question, question_type, options, complete = CourseLearn.objects.get_next_question(course_learn, session)

    if complete:
        return redirect('learn:success', course_learn_id=course_learn.pk, session=session)

    return super().get(*args, **kwargs)

答案 1 :(得分:0)

使用render_to_response解决了这个问题。对于那些可能需要它的人,在类

中添加一个函数
def render_to_response(self, context, **response_kwargs):
    if context['complete']:
        return redirect(reverse('learn:success',
                        kwargs={
                            'course_learn_id': context['course_learn'].pk,
                            'session': context['session']
                        }))
    return super(LearnQuestion, self).render_to_response(context, **response_kwargs)

并从get_context_data()发送上下文数据

if complete:
    context['complete'] = complete
    context['course_learn'] = course_learn
    context['session'] = session

    return context