request.session没有将完整的querydict转移到另一个视图

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了request.session没有将完整的querydict转移到另一个视图相关的知识,希望对你有一定的参考价值。

我使用'post'提交表单并使用request.POST将其数据传输到另一个视图,但是当它到达第二个视图时我的querydict不完整。

厂景

def question_filter(request):
    if request.method == 'POST':
        print('before validation', request.POST)
        request.session['question_data'] = request.POST
        return HttpResponseRedirect(reverse('qapp:question_preview'))

视图2

def question_preview(request):
    all_questions = Questions.objects.all()
    question_data = request.session.get('question_data')
    print(question_data)
    question_pk_list = question_data['question_pk']
    preview_questions = all_questions.filter(id__in=question_pk_list)
    ...
    return render(request,'apps/qapp/question_preview.html', {somecontext})

我在这里做错了吗?

更新:

before validation <QueryDict: {'topics_all': ['1', '2'], 'csrfmiddlewaretoken': ['...'], 'subtopics_all': ['4', '2'], 'classroom': ['3'], 'difficulty': ['l', 'm']}>
[28/Feb/2018 17:17:39] "POST /question/filter/ HTTP/1.1" 302 0

(in the second view)question data {'topics_all': '2', 'csrfmiddlewaretoken': '...', 'difficulty': 'm', 'subtopics_all': '2', 'classroom': '3'}
答案

你不能发送所有这样的post data,因为你有list inside your input names,你必须以不同的方式访问每个名称并将它们设置在session

request.session['question_data'] = request.POST.getlist('topics_all')

其他input names相同,然后在第二个视图中使用键访问

另一答案

默认情况下不会保存会话。添加request.session.modified = True

def question_filter(request):
    if request.method == 'POST':
        print('before validation', request.POST)
        request.session['question_data'] = request.POST
        request.session.modified = True
        return HttpResponseRedirect(reverse('qapp:question_preview'))

https://docs.djangoproject.com/en/2.0/topics/http/sessions/#when-sessions-are-saved

编辑:

你可以使用json破解它:

import json

def question_filter(request):
    if request.method == 'POST':
        print('before validation', request.POST)
        request.session['question_data'] = json.dumps(request.POST)
        return HttpResponseRedirect(reverse('qapp:question_preview'))

def question_preview(request):
    all_questions = Questions.objects.all()
    question_data = json.loads(request.session.get('question_data'))
    print(question_data)
    question_pk_list = question_data['question_pk']
    preview_questions = all_questions.filter(id__in=question_pk_list)
    ...
    return render(request,'apps/qapp/question_preview.html', {somecontext})

以上是关于request.session没有将完整的querydict转移到另一个视图的主要内容,如果未能解决你的问题,请参考以下文章

来自 Python request.session() 的请求没有记录在 Charles 中

session

Django REST 框架、JWT 和 request.session

25session练习

session小记

从 backend.get_user 访问 request.session