Are there forms that use the POST method needed to protect CSRF? I follow the book, and code examples throw 403 errors. I did some searches and it seems that I need to enable CSRF in all my forms.
My questions:
Does Django now require all POST forms to be CSRF protected?
All I have to do for this is add 'django.middleware.csrf.CsrfViewMiddleware', return render_to_response (template, dictionary, context_instance = RequestContext (request) and add '{% csrf_token%}' to the appropriate form? Am I- then missed here?
When I do this, the form works fine. When any of these parts is missing, it fails 403. I just want to make sure that I do it RIGHT. :)
Thanks in advance.
edit:
For some reason, this code does not make sense to me, but it does not return any errors. Please ignore the primitive check, as I did not get into the section of the book, which shows a more efficient way to do this.
def contact(request):
errors = []
if request.method == 'POST':
if not request.POST.get('subject',''):
errors.append('Enter a subject')
if not request.POST.get('message',''):
errors.append('Enter a message')
if request.POST.get('email', '') and '@' not in request.POST['email']:
errors.append('Enter a valid email address')
if not errors:
send_mail(
request.POST['subject'],
request.POST['message'],
request.POST.get('email', 'noreply@example.com'), ['siteownder@example.com'],)
return HttpResponseRedirect('/contact/thanks/')
return render_to_response('contact_form.html', { 'errors': errors }, context_instance=RequestContext(request))
My problem is with the last line of this view function. It is called only if request.method! = POST. This seems completely wrong to me. Shouldn't I call "context_instance = RequestContext (request)" when doing a POST?
source
share