django - 禁止 (403) CSRF 验证失败
问题描述
当我单击 add_tech.html 中的确定按钮时,它会将我重定向到upload_type.html。但是单击确定按钮时会显示错误。
错误 -
禁止 (403) CSRF 验证失败。请求中止。帮助 失败原因:CSRF 令牌丢失或不正确。
我的模板(add_tech.html) -
<form action="/uploads/type/" method="post">
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
我的模板(upload_type.html)-
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
</form>
我的视图.py -
def upload_type(request):
if request.method =='POST':
details = NameForm(request.POST)
if details.is_valid():
return render(request, "core/upload_type.html", {'form':details})
else:
details = NameForm()
return render(request, 'core/upload_type.html', {'form': details})
我的 Url.py -
urlpatterns = [
url(r'^uploads/type/$', views.upload_type, name='upload_type'),]
我的 form.py -
from uploads.core.models import Name
class NameForm(forms.ModelForm):
class Meta:
model = Name
fields = ('your_name', )
我的模型.py-
class Name(models.Model):
your_name = models.CharField(max_length=100)
解决方案
您需要在 django 模板中为您的 post 方法提供这样的 csrf 令牌
<form action="/uploads/type/" method="post">
{% csrf_token %}
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
推荐阅读
- java - 如何在不删除重复项的情况下对列表进行排序?
- wix - WiX 安装程序:如何在 WixUI_InstallDir 模式下隐藏/删除欢迎对话框
- c++ - 在异常处理程序中抛出异常仅在释放模式下失败
- firebase - 使用 Glide 加载 Firebase 存储映像会产生计费费用吗?
- java - 在 Spring AOP 中使用 @AfterReturning 修改类中的值
- google-cloud-platform - GKE 错误:版本“cloud.google.com/v1”中类型“BackendConfig”没有匹配项
- javascript - 对所有操作系统的网站仅使用一种字体 - 需要哪些文件?
- django - django-elasticsearch-dsl-drf 建议 url 给出 404 错误
- f# - F# Canopy:不拾取某些页面元素
- image-processing - 将 2D 图像变形到另一个图像上