Django:CSRF 令牌丢失或不正确 [英] Django: CSRF token missing or incorrect
本文介绍了Django:CSRF 令牌丢失或不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
错误位于 http://127.0.0.1:8000/fileupload/form.py
我有 1.3 版的 django.我曾尝试指定 localhost:8000 如其他人的问题所述,但这对我不起作用.我正在尝试使用文件上传表单,但我收到一个错误,提示 form.py 没有 CSRF 令牌.
I have version 1.3 of django. I have tried specifying localhost:8000 as stated in someone else's question but this did not work for me. I am trying to have a file upload form but I am receiving an error that form.py does not have the CSRF token.
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']})
上传.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 %}
我很困惑,请告诉我一些可以尝试的事情.谢谢
I am very stumped please tell me some things to try. Thank You
推荐答案
你需要在render_to_response中为csrf_token
You need to pass RequestContext
in render_to_response for csrf_token
为此:(views.py)
from django.template import RequestContext
...
return render_to_response('fileupload/upload.html', {'form': c['UploadFileForm']}, RequestContext(request))
# Added RequestContext
这会将 csrf 的令牌传递给模板.
This passes the token for csrf to the template.
这篇关于Django:CSRF 令牌丢失或不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文