2017-04-13 99 views
0

我看過一些論壇和帖子,但仍然無法得到它的處理。 Here in django doc,它說Django:CSRF不正確或丟失

在MIDDLEWARE設置中默認激活CSRF中間件。如果您覆蓋該設置,請記住'django.middleware.csrf.CsrfViewMiddleware'應該出現在任何視圖之前>假定已處理CSRF攻擊的中間件。

如果禁用它,這是不推薦的,你可以使用你想要保護(見下文),尤其是意見csrf_protect()。

在使用一個POST形式的任何模板,使用csrf_token標籤>元素中,如果表單是用於內部URL,例如:

表單動作 {%csrf_token%}

基於此,在我的html模板中,我只是:

<form id='frm' name='frm' method="post" action="{% url 'gettip' %}" > 
     {% csrf_token %} 

<input type="text" name="tipid" name="tipid"> 
<input type="submit" value="Get Tip Value"/> 
</form> 

我期望CSRF_token創建隱藏元素,因爲中間件已經加載。我在窗體中看不到任何元素,並且出現CSRF錯誤。

表單不與任何模型關聯。我還沒有使用forms.py。我目前的觀點只是輸出一些東西:

def gettip(request): 

    if request.POST: 
     return HttpResponse('You requested a tip') 

#from a weblink, i was told to add the following but it made no difference 
context = {} 
return render_to_response('tip.html',context, context_instance=RequestContext(request)) 

我得到的錯誤顯然是CSRF失蹤因爲隱藏的元素根本就沒有。

我正在從PHP遷移,這給我很難。雖然我的表單不適用於登錄目的,但我同意couldn't get this one to work either錯誤。我在Django 1.10上,只是想在表單提交時得到肯定的答覆。

+1

gettip是渲染模板的視圖嗎?如果沒有,請顯示那個。 –

+0

''context_instance'已從Django 1.10中的'render_to_response'中移除,因此該視圖根本無法工作。 – Alasdair

回答

0

請勿使用render_to_response,它已過時。改爲使用render

from django.shortcuts import render 

def gettip(request): 

    if request.POST: 
     return HttpResponse('You requested a tip') 

    context = {} 
    return render(request, 'tip.html', context) 

如果包含表單的模板由另一個視圖呈現,那麼您也必須修復該視圖。

+0

謝謝夥計們。更好地切換回PHP ...我最終得到了CSRF,但沒有形成元素......有點不一致。稍後有望看到它。 –

+0

如果您再次嘗試Django,請確保您使用的任何書籍或教程都至少爲Django 1.8編寫。您鏈接到的登錄表單教程是從2013年開始的,所以過時了。 – Alasdair

+0

按照django文檔(Atleast前4部分)。最適合學習django.https://docs.djangoproject.com/en/1.11/intro/tutorial01/。 – shadow0359

相關問題