錯誤是在位置http://127.0.0.1:8000/fileupload/form.pyDjango:CSRF令牌丟失或不正確
我有django的1.3版本。我曾嘗試在別人的問題中指定localhost:8000,但這不適用於我。我想要一個文件上傳的形式,但我收到一個錯誤,form.py沒有CSRF令牌。
form.py:
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
views.py:
def upload_file(request):
c = {}
c.update(csrf(request))
if (not request.user.is_authenticated()) or (request.user == None):
return HttpResponseRedirect("/?error=11")
if request.method == 'POST':
form = c['UploadFileForm'] = UploadFileForm(request.POST, request.FILES, c, context_instance=RequestContext(request))
if c['UploadFileForm'].is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = c['UploadFileForm'] = UploadFileForm()
return render_to_response('fileupload/upload.html', {'form': c['UploadFileForm']})
upload.html:
{% block main_content %}
<form action="fileupload/form.py" enctype="multipart/form-data" method="POST">
{% csrf_token %}
<table>
<tr><td>Title:</td><td><input type="text" name="title" /></td></tr>
<tr><td>File:</td><td><input type="file" name="file" /></td></tr>
</table>
<input type="submit" value="Submit" class = "float_right button_input" />
</form>
{% endblock main_content %}
我很爲難,請告訴我一些東西去嘗試。謝謝
您已經在模板中使用了'{%csrf_token%}',所以這應該起作用。 –
加上RequestContext我得到一個類型錯誤__init __()得到了一個意外的關鍵字參數'context_instance' – user1072646
謝謝,我只是想通了。它像你說的那樣添加RequestContext(request),並從if語句中刪除c和context_instance =。如果你改變你的答案,包括我會標記它是正確的。 – user1072646