Nick Bewley
Nick Bewley

Reputation: 9289

"CSRF verification failed. CSRF token missing or incorrect." Django

I am trying to create a Django app based on the Django Classifieds App, but am getting an error when trying to submit the form: CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect.

I do have a {% csrf_token %} in the form:

<form method="post" action="{% url classifieds.views.create.checkout ad.pk %}">
 {% csrf_token %}
  <table>
   {{ form }}
     <tr>
     <th><label>Total:</label></th>
     <td><div id="total">Choose options above</div></td>
     </tr>
  </table>
</form>

I also am using from django.template import RequestContext

I also have included 'django.middleware.csrf.CsrfViewMiddleware', in the MIDDLEWARE_CLASSES in my settings.py

What else could I be missing to properly submit the form?

The function looks like:

def checkout(request, adId):
   ad = get_object_or_404(Ad, pk=adId)
   if request.method == 'POST':
    form = CheckoutForm(request.POST)
    if form.is_valid():

 ...

  payment.save()

  if django_settings.DEBUG:
    paypal_form = PayPalPaymentsForm(initial=paypal_values).sandbox()
  else:
    paypal_form = PayPalPaymentsForm(initial=paypal_values).render()

  return render_to_response('classifieds/paypal.html', {'form': paypal_form}, context_instance=RequestContext(request))
else:
  form = CheckoutForm()

return render_to_response('classifieds/checkout.html', {'ad': ad, 'form': form}, context_instance=RequestContext(request))

Thank you for your suggestions.

Upvotes: 2

Views: 5421

Answers (1)

Mp0int
Mp0int

Reputation: 18727

Did you use correct RequestContext, i am not sure if the problem is that, but you may check it too. Step 3 of how to use it

  • In the corresponding view functions, ensure that the 'django.core.context_processors.csrf' context processor is being used. Usually, this can be done in one of two ways:

    1. Use RequestContext, which always uses 'django.core.context_processors.csrf' (no matter what your TEMPLATE_CONTEXT_PROCESSORS setting). If you are using generic views or contrib apps, you are covered already, since these apps use RequestContext throughout

Upvotes: 3

Related Questions