Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

python - CSRF token missing or incorrect, even after including the token tag

I am getting a 'CSRF token missing or incorrect' error, but I have already added the {% csrf_token%} tag in the web form. Any idea why I still face this error?

def index(request):
    if request.method == 'POST':
        form = RequestForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'index.html')
    else:
        form = RequestForm()
    return render(request, 'index.html', {'form': form})`

I cannot post the template, but I use the token as shown in line below

<form id="reqForm" action="" method="POST" enctype="text/plain">{% csrf_token %}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like your problem is enctype="text/plain" in your form. The CSRF protection assumes that the post data is form encoded.

The simplest fix is to remove that entirely, which is equivalent to:

enctype="enctype=application/x-www-form-urlencoded"

If you were uploading files in your form you would use:

enctype="multipart/form-data"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...