当前位置:  开发笔记 > 编程语言 > 正文

Django:CSRF令牌丢失或不正确

如何解决《Django:CSRF令牌丢失或不正确》经验,为你挑选了1个好方法。

错误位于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 %}


  
{% csrf_token %}
Title:
File:
{% endblock main_content %}

我很难过,请告诉我一些尝试的事情.谢谢



1> Yugal Jindle..:

您需要传入RequestContextrender_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的标记传递给模板.

推荐阅读
虎仔球妈_459
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有