I'm new to Django and I'm still trying to get to grips with its features. I've created very simple project with Django 1.4.2 which has index page with simple form where you enter something and results page where your input is displayed after submission (the code is below).
After submission, I get error 403 and the following message:
A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.")
index.html
<!DOCTYPE html>
<head>
<title>Index page</title>
</head>
<body>
<div id="header">Welcome to index page</div>
<div id="content">
<p>Enter your name</p>
<form action="/result/" method="post" accept-charset="utf-8">{% csrf_token %}
<input type="text" name="answer">
<input type="submit" value="Send!">
</form>
</div>
</body>
result.html
<!DOCTYPE html>
<head>
<title>Result page</title>
</head>
<body>
<div id="header">Here is the result</div>
<div id="content">
<p>Your name is: {{ answer }}</p>
</div>
</body>
views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
def index(request):
return render_to_response('index.html')
def result(request):
p = request.POST['answer']
return render_to_response('result.html', {'answer': p}, context_instance=RequestContext(request))
I've looked into documentation and various examples on the Internet, but I don't understand what I'm doing wrong. If I disable django.middleware.csrf.CsrfViewMiddleware in settings.py, I get exactly what I want, but that's not the answer I'm looking for.
I appreciate help from more experienced Django ninjas :-)
Your
index.html
is rendered withoutRequestContext
. Try this:I also recomend you to use more convenient shortcut
render
:From docs:
EDIT:
Thanks @nerdwaller for mentioning, newer versions now needs: