首页 > 解决方案 > 禁止 (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)

标签: djangocsrf

解决方案


您需要在 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>   

推荐阅读