2013-07-15 54 views
0

我在寫一個Django應用程序。這裏是我的代碼:表單提交中的Django CSRF錯誤

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/),並試圖解決這個問題,但我不能我在做什麼錯在這裏

感謝

UPDATE:。?。更新視圖。 。PY功能edit_modules和update_modules edit_modules是一個呈現形式和update_modules是一個處理它吧,我沒有得到CSRF錯誤我現在得到的錯誤:空模塊名

更新:我是能夠修復它,我正在使用一個vie w呈現表單,另一個表單處理表單。我不得不將上下文添加到呈現表單的第一個視圖中。

回答

3

你需要一個RequestContext在你的update_module視圖,而不是一個普通的舊HttpResponse。如果您使用方便的render shortcut,它會自動添加。在Django教程中有一個很好和快速的介紹。 A shortcut: render()

+0

我是否需要傳遞一個實際的模板html文件才能使其工作?我不能僅僅傳遞一些文本消息而不必使用實際的HTML文件? – Blueboye

+0

你可能應該定義一個合適的HTML模板,它不需要花一點時間在模板目錄中創建一個模板! –

+0

是的,我剛剛做了,並在視圖中我更新了代碼「return render(request,'updated.html')」。 Sill相同的CSRF錯誤。我還導入了「from django.shortcuts import render」 – Blueboye

0

您可以啓用請求上下文的過程中你的settings.py

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

,這樣你就不必做:

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

相反,簡單地說: 選擇render_to_response回報('my_template.html ', my_data_dictionary)

此外,請確保在MIDDLE中啓用了'django.middleware.csrf.CsrfViewMiddleware' WARE_CLASSES in your settings.py