Search code examples
pythondjangocsrfdjango-csrf

csrf failure using csrf and Request Context


I have tried all I can gather from the forums, still need help: I keep getting the CSRF token missing or incorrect error when I submit a form. It used to be working fine and then I made some changes and now I cant get back.. I am using {% csrf_token %} and RequestContext. I have tried using reverse, i checked the settings.py middleware for the csrf middleware, tried restarting the server, tried using HttpResponse instead of HttpResponseRedirect and template.render(), tried a url path instead of the {% url %} tag. In other parts of my project I am not even using RequestContext and it works fine..

signup_page.html:

<p>Sign Up Below
</p>
    <form action={% url 'signup_page' %} method="post">
    {% csrf_token %}

    ....

    Email
    <input type="email" name="email" required="true"><br><br>

    <input type="submit" value="POST">

</form>

views.py

def signup_page(request):
    template = loader.get_template('user_app/signup_page.html')

    if request.method == "POST":
        ...
        email = request.POST['email']
        kwargs = {
            'username':username, 'password':password, 'first_name':first_name,
            'last_name':last_name, 'email':email
        }
        new_user = User.objects.create(**kwargs)
        new_user.save()

        context = {
            'text':"POST", 'first_name':first_name
        }

        return HttpResponseRedirect(render('signup_page', context, context_instance =RequestContext(request)))
    else:
        return HttpResponse(template.render(RequestContext(request)))

urls.py:

from django.conf.urls import url
from user_app.views import signup_page, profile

urlpatterns = [
    url(r'^signup', signup_page, name="signup_page"),
    url(r'^profile', profile, name="profile")
]

Solution

  • from django.shortcuts import render
    
    #create your views here
    def your_function(request):
        #do whatever you want here...
        context = {'any_data': 'you_want_to_send'}
        return render(request,'your.html',context)