如何在Django中正确使用context_processor

时间:2019-05-19 07:07:05

标签: python django

在这里,如果表单提交成功,但是此代码无法正常工作,我正尝试重定向到另一页。该代码保存了表单数据发送的电子邮件,一切正常,但问题是在重定向到另一页时形式成功。我得到的错误是:

  

Django版本:2.0.6
  异常类型:ValueError
  异常值:

字典更新序列元素#0的长度为0;需要2个

  

context_processor.py

def volunteer_page2(request):
    volunteer = Volunteer.objects.all().order_by('date')

    if request.method == 'POST':
        form = VForm(request.POST or None)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']

            message = "{0} with email address {1} has sent you new message \n\n{2}".format(name, email, form.cleaned_data['message'])

            form.save(commit = False)
            try:
                send_mail(name, message, 'appname <settings.EMAIL_HOST_USER>', ['myemail'])
            except:
                return HttpResponse('Invalid header found')

            form.save()
            messages.success(request, 'Success')
            return redirect('volunteer_page')
        else:
             messages.error(request, "Sorry try again")
    else:
        form = VForm()

    return  {'volunteer': volunteer, 'form':form}
  

views.py

def about_page(request):
    about = About.objects.all().order_by('date')
    banner = Banner.objects.all()

    testimonial = Testimonial.objects.order_by('-pk')[0:2]
    nav = Nav.objects.all()
    footer = Footer.objects.all()

    latest_event2 = Events.objects.order_by('-pk')[0:2]

    context = {
        'about': about,

        'testimonial': testimonial,
        'footer':footer,
        'banner': banner,
        'nav': nav,
        'latest_event2': latest_event2,

    }

    return render(request, 'myapp/about.html', context)
  

settings.py

'myapp.context_processor.volunteer_page2'

1 个答案:

答案 0 :(得分:0)

Django的上下文处理器应始终返回字典。在您的代码中,您还将返回HttpResponse。这是问题。