簡體   English   中英

Django - 403 Forbidden CSRF驗證失敗

[英]Django - 403 Forbidden CSRF verification failed

我在Django有一個聯系表格供我的網站使用,當我在本地進行測試時它工作正常,但現在當我嘗試提交我的聯系表單“live”時,總是會出現403 Forbidden CSRF驗證失敗。

視圖:

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email', 'noreply@example.org'),
                ['example@gmail.com'],
            )
            return HttpResponseRedirect('/thanks/')
    else:
        form = ContactForm()
    return render(request, 'contact/contact.html', {'form': form})

contact.html

{% extends 'site_base.html' %}

{% block head_title %}Contact{% endblock %}

{% block body %}

      <h2>Contact Us</h2>
      <p>To send us a message, fill out the below form.</p>

    {% if form.errors %}
        <p style="color: red;">
            Please correct the error{{ form.errors|pluralize }} below.
        </p>
    {% endif %}

    <form action="" method="POST">
    {% csrf_token %}
        <table>
            {{ form.as_table }}
        </table>
        <br />
        <button type="submit" value="Submit" class="btn btn-primary">Submit</button>
    </form>    

{% endblock %}

設置(我認為相關的設置):

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
MIDDLEWARE_CLASSES = [
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

在試圖排除某些事情之后,這就是我發現的。 當我注釋掉SESSION_COOKIE_SECURE = TRUECSRF_COOKIE_SECURE = TRUESESSION_EXPIRE_AT_BROWSER_CLOSE = TRUE它沒有問題。

如果我只是注釋掉CSRF_COOKIE_SECURE = TRUE它可以正常工作。 我處理CSRF的方式似乎有點奇怪......任何幫助都會很棒。

對我來說聽起來像網站不是https,如果它在你注釋掉那條線時有效嗎? CSRF_COOKIE_SECURE=True使csrf令牌適用於每個文檔的ssl https://docs.djangoproject.com/en/1.7/ref/settings/#csrf-cookie-secure

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM