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
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..
When you found this type of message , it means CSRF token missing or incorrect. So you have two choices.
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.
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',
)
1) {% csrf_token %} is not in template -- or -- 2) {% csrf_token %} is outside of html-form
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');
}