错误位于http://127.0.0.1:8000/fileupload/form.py
我有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 %}{% endblock main_content %}
我很难过,请告诉我一些尝试的事情.谢谢
您需要传入RequestContext
render_to_responsecsrf_token
为此:(views.py)
from django.template import RequestContext ... return render_to_response('fileupload/upload.html', {'form': c['UploadFileForm']}, RequestContext(request)) # Added RequestContext
这会将csrf的标记传递给模板.