Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 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 Reply

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...