禁止(403)CSRF验证失败。使用djang中止请求

2024-04-25 17:07:38 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我是python和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.

在视图.py在

^{pr2}$

在网址.py在

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

在表单.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

在网址.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>

Tags: todjangofrompyimportformforis
1条回答
网友
1楼 · 发布于 2024-04-25 17:07:38

您正在向表单添加csrf令牌,但没有在view函数中提供它。试试这个:

from django.views.decorators.csrf import csrf_protect

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

相关问题 更多 >