Skip to main content
 首页 » 编程设计

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

2024年08月30日21lidabo

我正在尝试基于 Django Classifieds App 创建一个 Django 应用程序,但在尝试提交表单时出现错误:CSRF 验证失败。请求中止。给出的失败原因:CSRF token 丢失或不正确。

我确实有一个 {% csrf_token %} 的形式:

<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> 

我也在使用 from django.template import RequestContext

我还在 settings.py 的 MIDDLEWARE_CLASSES 中包含了 'django.middleware.csrf.CsrfViewMiddleware',

我还缺少什么才能正确提交表单?

函数如下所示:

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)) 

感谢您的建议。

请您参考如下方法:

你是否使用了正确的RequestContext,我不确定是不是这个问题,但你也可以检查一下。 how to use it 的第 3 步

  • 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