2011-03-05 66 views
1

我得到了「CSRF令牌丟失或不正確」的錯誤,每當我嘗試下面的代碼時:在我的形式Django的CSRF問題上傳文件

def format(request): 
    if not request.user.is_authenticated(): 
     return HttpResponseRedirect('/formatter/login/?next=%s' % request.path) 
    else: 
     if request.method == 'POST': 
      csv_file = request.FILES['file'] 
      filedata = format_csv_file(csv_file) 
      [...] 
     response = HttpResponse(filedata) 
     response['Content-Type'] = 'application/dat' 
     response['Content-Disposition'] = 'attachment; filename="' + str(datestamp) + ".dat\n\n" 
     return response 

我已經得到了{%csrf_token%}也。我只是不知道我在這裏錯過了什麼。任何幫助將不勝感激。謝謝!

編輯:按照要求,這裏呈現的模板的觀點:

def main_view(request): 
if not request.user.is_authenticated(): 
    return HttpResponseRedirect('/formatter/login/?next=%s' % request.path) 
else: 
    return render_to_response('main.html') 

而這裏的模板(相關部分):

<form enctype="multipart/form-data" action="format/" method="POST">{% csrf_token %} 
    <p>Please select a file to convert: <input type="file" name="file" onchange="this.form.submit()"></p> 
    <p class="smalltext"><i>**Upon selecting a file to convert, you will be prompted to download the finished result</i> 
</form> 
+1

向我們展示呈現表單的代碼。 – AndiDog 2011-03-05 14:56:26

+1

您可以向我們展示HTMl或其呈現後的表單嗎?它可能是中間件或context_processors沒有正確安裝 – crgwbr 2011-03-05 15:01:16

+1

你打敗了我秒。沒有什麼比我們自己找到答案。 – 2011-03-05 15:09:52

回答

1

我已經回答了我的問題; RequestContext未在呈現表單模板的視圖中使用。以下是更正後的版本:

def main_view(request): 
if not request.user.is_authenticated(): 
    return HttpResponseRedirect('/formatter/login/?next=%s' % request.path) 
else: 
    return render_to_response('main.html', context_instance=RequestContext(request))