简体   繁体   中英

“CSRF token missing or incorrect”

EDIT SOLVED : I feel like such a moron. I originally created two separate views: one for input and one for output. I had been handling all of the code here in the output view even though I rearranged my url and template to just reuse the input view... SORRY EVERYONE. It works fine now...


I'm running on localhost, and when I submit my form I'm getting a "CSRF token missing" error. I've read the documentation and some stackoverflows. I have already solved most of the common issues:

  • I have the csrf token in my template (when loaded the template has inserted exactly this: <input type="hidden" name="csrfmiddlewaretoken" value=""> )
  • I am using render_to_response with render_to_response('_template_',{_data_:'_data_'},context_instance=RequestContext(request))
  • I do have have RequestContext imported to my views
  • I do have 'django.middleware.csrf.CsrfViewMiddleware' in my settings.

Anyone have any idea what I could be missing?

Here is my form:

<form action="" method="post">
            {% csrf_token %}
            <input type="text" name="q">
            <input type="submit" value = "Submit">
        </form>

Here is my view:

def view_workout(request):
    errors = []
    if request.method == 'POST':
        q = request.POST['q']
        if not request.POST.get('q', ''):
            errors.append('Please complete all required fields')
            return render_to_response('swimsets/view_workout.html',{
                'error': errors
            },context_instance=RequestContext(request))
        else:
            return render_to_response('swimsets/view_workout.html',{
                'query': q
            },context_instance=RequestContext(request))

    else:

        return render_to_response('swimsets/view_workout.html', {

    },context_instance=RequestContext(request))

Here is my settings:

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

您可能缺少CsrfResponseMiddleware,基于相关问题的答案是否在Django 1.2中仍然需要{%csrf_token%} CSRF保护标记?

您还可能需要将csrf导入视图中:

from django.core.context_processors import csrf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM