[Fixed]-Getting error 403 (CSRF token missing or incorrect)

1👍

Your problem is render_to_reponse. It doesn’t have the context instance you can add it, but render handles this for you so why not just it instead. Also you can restructure your view to be a bit cleaner.

Here’s one example.

def send_email(request):

    if request.method == 'POST':
        form = EmailForm(request.POST, request.FILES)   
        if form.is_valid():
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            email = form.cleaned_data['email']
            attach = request.FILES['attach']
            try:
                mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email])
                mail.attach(attach.name, attach.read(), attach.content_type)
                mail.send()
                messages.succes(request, 'Sent an email to %s' % email)
            except:
                messages.error(request, 'Either the attachment is too  big or corrupt')
    else:
        form = EmailForm()
        messages.info(request, "Send an email!")
    return render(request, 'mail_form.html', {'email_form': form})

Then you can use {% if messages %} in your template to display your messages to the user / iterate over them and display.

messages here is from django.contrib so you’d need to do from django.contrib import messages

0👍

  1. Use render_to_response from django.shortcuts
  2. Use in render_to_response context_instance = RequestContext(request)

This must fix your problem with csrf token or read https://docs.djangoproject.com/ja/1.9/ref/csrf/

0👍

Just modify your view.py like this

from django.shortcuts import render
from django.template import RequestContext
def send_email(request):
if request.method != 'POST':
    form = forms.EmailForm()
    return render_to_response('mail_form.html', {'email_form': form}, context_instance=RequestContext(request))

......
......

0👍

What version of django are you using?

Well, obviously you are using render() in part of your code. The problem is in your GET code–you are using render_to_response():

if request.method != 'POST':
    form = EmailForm()
    return render_to_response('mail_form.html', {'email_form': form})

Instead use render():

    return render(request, 'mail_form.html', {'email_form': form} )

See the example in the Django docs.

The reason you need to do that is because with csrf tokens you need to:

  1. Insert the csrf token in your form.

  2. Include the csrf token as a cookie in the headers of the request/response.

render() accomplishes #2, but render_to_response() does not–unless you specifically tell it to, which you did not. In any case, the django 1.9 docs state:

render_to_response()

This function preceded the introduction of render() and works
similarly except that it doesn’t make the request available in the
response. It’s not recommended and is likely to be deprecated in the
future.

👤7stud

Leave a comment