升级后的Django CSRF失败1.9> 1.11

时间:2017-06-28 15:08:54

标签: 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>

1 个答案:

答案 0 :(得分:4)

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

  

在Django 1.10中更改:

     

为令牌添加了salting,并开始随每次请求更改它以防止BREACH攻击。

在您的表单生效之前,您必须先注销并重新登录才能生成新的盐渍令牌。

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

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