0

views.py

from django.shortcuts import render_to_response
from django.core.context_processors import csrf
def home(request):  
    c = {}
    c.update(csrf(request))
    if request.method == "POST":
        username = request.POST.get("username", '') 
        password = request.POST.get("password", '') 
        return render_to_response("login_home.html", {"username":username, "password":password})
    else:
        return render_to_response("login_home.html")

login_home.html

{% extends "base.html" %}
{% block page %}
    {{ name }}
    <form action = "/blog/home/" method = "POST">{% csrf_token %}
    <input type = "text" name = "username" placeholder = "username">
    <input type = "text" name = "password" placeholder = "password">
    <input type = "submit">
    </form>

    {{ username }}
    {{ password }}

{% endblock %}

urls.py

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
    url(r'^home/$', 'blog.views.home'),
)

^^Here are my files. The problem is the error i get once i submit the form:

Forbidden (403)
CSRF verification failed. Request aborted.

I am not exactly sure what i am forgetting or missing. I am guessing its somewhere in the views function. Can someone point put the bit i am missing?

Thanks for any help.

user2800761
  • 2,235
  • 2
  • 13
  • 8

1 Answers1

1

You need to either use a RequestContext or return the context you have created with c.update(csrf(request)):

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

  1. Use RequestContext, which always uses 'django.core.context_processors.csrf' (no matter what your TEMPLATE_CONTEXT_PROCESSORS setting). If you are using generic views or contrib apps, you are covered already, since these apps use RequestContext throughout.

  2. Manually import and use the processor to generate the CSRF token and add it to the template context. e.g....

return render_to_response("login_home.html",
    {"username":username, "password":password}
    context_instance=RequestContext(request))
Community
  • 1
  • 1
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177