簡體   English   中英

表單提交時的Django CSRF錯誤

[英]Django CSRF error on form submission

我正在編寫Django應用。 這是我的代碼:

edit.module.html (模板;刪除多余的html標記):

<h1>Enter the HTML below</h1>
<form action="./update/" method="post">
    {% csrf_token %}
    <textarea cols='55' rows='15'></textarea>
    <input type='submit' value='Submit' />
</form>

urls.py

url(r'^myapp/update/$', 'myproj.myapp.views.update_module'),

view.py

from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.core.context_processors import csrf
from django.template import RequestContext

#Select the module you want to edit
def edit_modules(request):
    lpconf = {"module_to_edit" : "top"}
    return render_to_response('admin/edit.module.html', lpconf, context_instance=RequestContext(request))

def update_module(request):
    return render_to_response('admin/updated.html', context_instance=RequestContext(request))

提交表單時,出現CSRF錯誤:“ CSRF驗證失敗。請求中止。”

我遵循了Django文檔( https://docs.djangoproject.com/en/dev/ref/contrib/csrf/ )並試圖解決此問題,但我做不到。 我在這里做錯了什么?

謝謝。

更新:更新了view.py函數edit_modules和update_modules。 edit_modules是一個呈現表單的表單,update_modules是一個處理表單的表單。 現在,我沒有收到CSRF錯誤。 我現在收到錯誤: 空模塊名稱

更新:我能夠修復它。 我正在使用一個視圖來渲染表單,並使用另一個視圖來處理它。 我必須在渲染表單的第一個視圖中添加上下文。

您需要在update_module視圖中使用RequestContext ,而不是普通的HttpResponse 如果您使用方便的渲染快捷方式 ,它將自動添加。 Django教程對此有一個很好的介紹。 快捷方式:render()

您可以在settings.py中啟用請求上下文流程

TEMPLATE_CONTEXT_PROCESSORS = (...
    "django.core.context_processors.request")

因此您不必執行以下操作:

return render_to_response('my_template.html',
                      my_data_dictionary,
                      context_instance=RequestContext(request)

相反,只需:return render_to_response('my_template.html',my_data_dictionary)

另外,請確保您在settings.py中的MIDDLEWARE_CLASSES中啟用了“ django.middleware.csrf.CsrfViewMiddleware”

暫無
暫無

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

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