Forbidden (403) CSRF验证失败

Forbidden (403) CSRF verification failed

当我在 add_tech.html 中单击确定按钮时,它将在 upload_type.html 中重定向我。 但是点击确定按钮时显示错误。

错误 -

Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect.

我的模板(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>

我的View.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 模板中的 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>   

对于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 ships with an easy-to-use protection against Cross Site Request Forgeries. When submitting a form via POST with CSRF protection enabled you must use the csrf_token template tag as in the preceding example.