2
votes

Hello and thank you in advance. This is a follow up question from the following thread (not sure if I should have posted there or started a new thread...:

CSRF token missing or incorrect even though I have {% csrf_token %}

I am not sure what I need to do with the code to make csrfContext work. I am trying to use ModelForm to collect data to a model and write it to a MYSQL table. I am gettingthe error:

Reason given for failure:
    CSRF token missing or incorrect.

Here is the code:


    from django.shortcuts import render_to_response
    from djengo.template import RequestContext
    from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
    from acmetest.models import Player
    from acmetest.models import PickForm

    csrfContext = RequestContext(request)
    return render_to_response('makepick.html', csrfContext)

    def playerAdd(request, id=None):
        form = PickForm(request.POST or None,
                           instance=id and Player.objects.get(id=id))

        # Save new/edited pick
        if request.method == 'POST' and form.is_valid():
            form.save()
            return HttpResponseRedirect('/draft/')

        return render_to_response('makepick.html', {'form':form})

Again,

Thank you for your help!

dpbklyn

2
Just saw this addon-question. Not sure how/why the answer helped, but one thing I have to mention - assuming you cut/paste the code exactly, you misspelled django.template as djengo.template. It isn't invalid code, just typo'ed. (And you should be using RequestContext, if you're not).John C

2 Answers

1
votes

Update your code thusly:

from django.shortcuts import render
# from djengo.template import RequestContext <- this is not valid.

These two lines, as Yuji pointed out, are not valid python, and in addition they are not necessary if you use the render shortcut.

# csrfContext = RequestContext(request)
# return render_to_response('makepick.html', csrfContext)

Modify your return line:

 # return render_to_response('makepick.html', {'form':form})
   return render(request,'makepick.html',{'form':form})
0
votes

I'm assuming we're talking about the playerAdd view - you need to pass RequestContext to the response there.

def playerAdd(request, id=None):
    form = PickForm(request.POST or None,
                       instance=id and Player.objects.get(id=id))
    # Save new/edited pick
    if request.method == 'POST' and form.is_valid():
        form.save()
        return HttpResponseRedirect('/draft/')

    return render_to_response('makepick.html', RequestContext(request, {'form':form}))

The first lines in your code are hard to understand and doesn't even appear to be valid python. You can't use return from outside a function block.