简体   繁体   中英

how to use context_processor properly in django

Here I am trying to redirect to another page if the form is submitted successfully but this code is not working properly .The code saves the form data sends the email , everything is fine but the problem is while redirecting to another page if the form succeed. The error I get is:

Django Version: 2.0.6
Exception Type: ValueError
Exception Value:

dictionary update sequence element #0 has length 0; 2 is required

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'

Django's context processor should always return dictionary. In your code you are returning HttpResponse also. This is problem.

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