3
votes

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',
)
2
I just added it, deleted the views.pyc, restarted the localhost. still doesnt work. - InfinteScroll
I can't help but feel like the value of csrfmiddlewaretoken shouldn't be "". Can you try placing {{ csrf_token }} (notice double brackets, not percent signs) somewhere, and make sure it displays a real token? - Luke Sapan

2 Answers

1
votes

You might be missing CsrfResponseMiddleware, based on an answer in related question Is the {% csrf_token %} CSRF protection tag still necessary in Django 1.2?

1
votes

You also may need to import csrf into your view:

from django.core.context_processors import csrf