CSRF verification failed. Request aborted

后端 未结 10 1879
执笔经年
执笔经年 2020-12-01 13:04

I try to build a very simple website where one can add data into sqlite3 database. I have a POST form with two text input.

index.html:

{% if top_list         


        
相关标签:
10条回答
  • 2020-12-01 13:24

    One more nicest alternative way to fix this is to use '@csrf_exempt' annotation.

    With Django 3.1.1 you could just use @csrf_exempt on your method.

    from django.views.decorators.csrf import csrf_exempt
    
    @csrf_exempt
    def index(request):
    

    and you don't need to specify {% csrf_token %} in your html.

    happy learning..

    0 讨论(0)
  • 2020-12-01 13:29

    When you found this type of message , it means CSRF token missing or incorrect. So you have two choices.

    1. For POST forms, you need to ensure:

      • Your browser is accepting cookies.

      • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.

    2. The other simple way is just commented one line (NOT RECOMMENDED)('django.middleware.csrf.CsrfViewMiddleware') in MIDDLEWARE_CLASSES from setting tab.

      MIDDLEWARE_CLASSES = (
          'django.contrib.sessions.middleware.SessionMiddleware',
          'django.middleware.common.CommonMiddleware',
          # 'django.middleware.csrf.CsrfViewMiddleware',
          'django.contrib.auth.middleware.AuthenticationMiddleware',
          'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
          'django.contrib.messages.middleware.MessageMiddleware',
          'django.middleware.clickjacking.XFrameOptionsMiddleware',
      

      )

    0 讨论(0)
  • 2020-12-01 13:34

    1) {% csrf_token %} is not in template -- or -- 2) {% csrf_token %} is outside of html-form

    0 讨论(0)
  • 2020-12-01 13:38

    In your HTML header, add

    <meta name="csrf_token" content="{{ csrf_token }}">
    

    Then in your JS/angular config:

    app.config(function($httpProvider){
        $httpProvider.defaults.headers.post['X-CSRFToken'] = $('meta[name=csrf_token]').attr('content');
    }
    
    0 讨论(0)
提交回复
热议问题