2017-06-28 42 views
2

我刚刚升级的应用程序,我从1.9到1.11开发和正在对所有形式的职位不断得到错误:Django的CSRF升级失败后1.9> 1.11

CSRF token missing or incorrect. 

所有CSRF令牌是在做工精细1.9。下面是这个视图:

def contact(request): 
    subject = request.GET.get('subject', '') 
    contact_form = forms.ContactForm(subject=subject) 

    if request.POST: 
     contact_form = forms.ContactForm(request.POST) 

     if contact_form.is_valid(): 
      new_contact = contact_form.save() 
      logic.send_contact_message(new_contact, request) 
      messages.add_message(request, messages.SUCCESS, 'Your message has been sent.') 
      return redirect(reverse('contact')) 

    template = 'journal/contact.html' 
    context = { 
     'contact_form': contact_form, 
     'contacts': core_models.Contacts.objects.filter(content_type=request.content_type, 
                object_id=request.site_type.pk) 
    } 

    return render(request, template, context) 

这里是模板:

  <h4>{% trans "Contact" %}</h4> 
      <form method="POST"> 
       {% include "elements/forms/errors.html" with form=contact_form %} 
       {% csrf_token %} 
       <label for="id_recipient">{% trans "Who would you like to contact?" %}</label> 
       <select id="id_recipient" name="recipient"> 
        {% for contact in contacts %}<option value="{{ contact.email }}">{{ contact.name }}, {{ contact.role }}</option>{% endfor %} 
       </select> 
       {{ contact_form.sender|foundation }} 
       {{ contact_form.subject|foundation }} 
       {{ contact_form.body|foundation }} 
       {{ contact_form.are_you_a_robot|foundation }} 
       <button type="submit" class="success button">{% trans "Send Message" %}</button> 
      </form> 

回答

3

Django的1.10 introduced salted CSRF tokens that change every time the user logs in

改变在Django 1.10:

添加盐析令牌并开始更改每个请求以防止BREACH攻击。

您将不得不注销并重新生成一个新的腌制令牌,然后您的表单才能正常工作。

Melvyn建议您在评论中清除您的会议商店。这也可以,如果你有很多用户,这可能是一个更好的选择。

您可能还必须修改中间件设置以反映the new style introduced in Django 1.10old MIDDLEWARE_CLASSES setting is deprecated赞成MIDDLEWARE。确保'django.middleware.csrf.CsrfViewMiddleware'包含在您的MIDDLEWARE中。如果你有自定义的中间件(或者如果你使用的是使用旧式中间件的库),它将不得不更新。

+1

或清除会话存储(将注销所有用户)。痛苦,但必要。 – Melvyn

+0

伟大的观点,@Melvyn。如果有许多用户,这绝对会更好。谢谢! – Chris

+0

感谢您的支持,清除了会话表并清除了浏览器Cookie,但在尝试登录时仍然出现CSRF错误... – ajrbyers