2017-02-08 167 views
1

你好,我是用户python和Django。禁止(403)CSRF验证失败。请求使用django中止

我会按照这个question(Can I have a Django form without Model) 但为我的任务,我需要图像。 我会尝试运行我的代码,我有这个错误禁止(403):任何想法如何解决这个问题?

Forbidden (403) 
CSRF verification failed. Request aborted. 
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. 
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. 

views.py

from django.shortcuts import render 
from django.shortcuts import render_to_response 
from django.template import RequestContext 
from blog.forms import MyForm 

# Create your views here. 
def form_handle(request): 
    form = MyForm() 
    if request.method=='POST': 
     form = MyForm(request.POST) 
     if form.is_valid(): 
      cd = form.cleaned_data 
      #now in the object cd, you have the form as a dictionary. 
      a = cd.get('a') 
    return render_to_response('blog/calc.html', {'form': form}, RequestContext(request)) 

urls.py

from django.conf.urls import url 
from . import views 

forms.py

from django import forms 

class MyForm(forms.Form): #Note that it is not inheriting from forms.ModelForm 
    a = forms.ImageField() 
    #All my attributes here 

urls.py

urlpatterns = [ 
url(r'^$',views.form_handle, name='form_handle'), 

] 

HTML

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Title</title> 
</head> 
<body> 
<form action="" method="POST">{% csrf_token %} 
    {{form.as_p}} 
    <button type="submit">Submit</button> 
</form> 
</body> 
</html> 
+0

在你的看法中,当渲染你的模板时,通过'RequestContext'作为关键字参数。 'return'回复render_to_response('blog/calc.html',{'form':form},context_instance = RequestContext(request))' – anupsabraham

+1

使用'render_to_response('blog/calc.html',{'form': (请求,'blog/calc.html',{'form':form}'? –

+0

'render(request,'blog/calc.html',{ 'form':form})'不工作我接受这个错误'ValueError:视图blog.views.form_handle没有返回一个HttpResponse对象,它返回None而不是' – Mar

回答

0

要添加CSRF令牌的形式,但在视图功能没有提供它。试试这个:

from django.views.decorators.csrf import csrf_protect 

# Create your views here. 
@csrf_protect 
def form_handle(request): 
    form = MyForm() 
    ... 
相关问题