"Invalid CSRF token or invalid"

EDIT SOLVED : I feel like such a moron. Initially, I created two separate views: one for input and one for output. I handled all the code here in the output view, although I rebuilt my url and template to just reuse the input view ... AVOID EVERYTHING. Now it works fine ...


I run on localhost, and when I submit my form, I get the error "CSRF token missing". I read the documentation and some stackoverflows. I have already solved most common problems:

  • I have a token csrf in my template (when loading the template put it is 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 have a RequestContext imported into my views
  • I have 'django.middleware.csrf.CsrfViewMiddleware'in my settings.

Can anyone understand what I am 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 are 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',
)
+3
source share
2 answers

Perhaps you are missing CsrfResponseMiddleware, based on the answer on a related question. Is there another {Csrf_token%} CSRF security tag in Django 1.2?

+1
source

You may also need to import csrf into your view:

from django.core.context_processors import csrf
+1
source

All Articles