Search code examples
pythondjangodjango-csrf

csrf token Follow up


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


Solution

  • 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})