【问题标题】:Forbidden (403) CSRF verification failed禁止 (403) CSRF 验证失败
【发布时间】:2020-05-04 05:34:54
【问题描述】:

当我点击 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', )

我的 Models.py-

class Name(models.Model):
    your_name = models.CharField(max_length=100)

【问题讨论】:

    标签: django csrf


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      对于 POST 请求,需要 csrf 令牌。所以在你的模板中,添加`{% csrf_token %}。

      <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>  
      

      来自Docs

      Django 附带一个易于使用的跨站点请求保护 伪造品。 通过带有 CSRF 保护的 POST 提交表单时 启用您必须使用 csrf_token 模板标签,如前所述 例子。

      【讨论】:

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