【问题标题】:Forbidden (403) CSRF verification failed. Request aborted using django禁止 (403) CSRF 验证失败。使用 django 中止请求
【发布时间】:2017-06-26 09:13:26
【问题描述】:

你好,我是用户 python 和 Django。

我会关注这个question(Can I have a Django form without Model) 但对于我的任务,我需要图像。 我会尝试运行我的代码,但我有这个错误 Forbidden (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>

【问题讨论】:

  • 在您看来,在渲染模板时,将RequestContext 作为关键字参数传递。 return render_to_response('blog/calc.html', {'form': form}, context_instance=RequestContext(request))
  • 使用render_to_response('blog/calc.html', {'form': form}, RequestContext(request)) 而不仅仅是render(request, 'blog/calc.html', {'form': form} 有什么特别的原因吗?
  • render(request, 'blog/calc.html', {'form': form}) 不起作用我认为错误` ValueError:视图 blog.views.form_handle 没有返回 HttpResponse 对象。它返回 None `

标签: python django


【解决方案1】:

您正在向表单添加一个 csrf 令牌,但未在视图函数中提供它。试试这个:

from django.views.decorators.csrf import csrf_protect

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-05
    • 2018-06-06
    • 2016-08-27
    • 2019-07-22
    • 2016-05-12
    • 2014-11-15
    • 2017-08-06
    相关资源
    最近更新 更多