2017-06-28 38 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