Using #csrf_exempt and creating a CSRF token in the same view - django

I am expecting a POST from a 3rd party server. I understand that I need to use the #csrf_exempt decorator to allow for a post from a 3rd party server. I'm using Django 1.4 and Python 2.7 on Ubuntu 12.04.
Now, my view is going to generate an un-bound form that will contain fields for a user to populate as well as hidden fields containing information from the original POST. So, the first POST will initiate a second POST.
The second POST is going to be sent from my server to another view on my server. I'm trying to figure out how to generate a CSRF token for my form.
I'm trying to do exactly what I've read in the documentation.
My code from views.py:
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
from gateway_interface.post_handling import PostHandling
#csrf_exempt
def requestNewPaymentInfo(request):
c = {}
c.update(csrf(request))
# Gather information posted
if (request.method == "POST"):
# Create the initialization dictionary based on POST values
postHandling = PostHandling()
post_dict = postHandling.createDictionary(request)
# Create the form
form = addPaymentForm(initial = post_dict)
return render_to_response('requestNewPaymentInfo.html', { 'form' : form }, c)
What do you do on the template side now?!? Again, from the documentation I thought I should do the following:
<form action="/addPayment/" method="post">
{% csrf_token %}
</form>
I test this by doing a POST from a 3rd party server. Sometimes I see the form fully generated with what appears to be a valid CSRF token.
Sometimes I see a failure that looks like this:
Django Version: 1.4
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'gateway_interface')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "/home/tokeniz/tokeniz/gateway_interface/views.py" in requestNewPaymentInfo
64. return render_to_response('requestNewPaymentInfo.html', { 'form' : form }, c)
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render_to_response
20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
178. context_instance.pop()
Exception Type: TypeError at /requestNewPaymentInfo/
Exception Value: pop expected at least 1 arguments, got 0
Then I will eventually get this error:
Forbidden (403)
CSRF verification failed. Request aborted.
Once I receive the CSRF verification failed error I will continue to get this error until I clear the cookies and start over.
Can anyone tell me what I'm doing wrong? I can see it has something to do with how I generate the CSRF token. I don't understand how the process works based on what is in the documentation. What is c in my view? An empty dictionary that I'm populating with information and passing to render_to_response. Ok, but how is that being used in the template?
Should my template have something like this:
<form action="/addPayment/" method="post">
{% c.csrf_token %}
</form>
If not, why? How does Django know that this c contains the CSRF token?
Any help would be greatly appreciated.

To fix your problem, let me can clarify some things.
Django's template system in a nutshell works with two pieces of data: context and template.
When you put a variable to display in your template file, like {{ foo }}, django is going to look inside corresponding context instance, which a dict on steroids, to find the value of that variable.
Now to render_to_response, what you pass to it as a second parameter, a dict, is essentially the data you want to put in template's context, and so it will be available for you. The third paramater is a Context instance, not the data itself, it can be useful when you need to customize things.
Ok, so let's look at your example,
return render_to_response('requestNewPaymentInfo.html', { 'form' : form }, c)
Here, you made a mistake reading docs example, you put c as a context instance, not context data, hence your token didn't even make it to the template, and you got all those weird errors where django was expecting Context object, but only got dict.
So to fix, you just need to pass csrf token inside template data:
c.update({'form': form})
return render_to_response('requestNewPaymentInfo.html', c)
And inside the template:
{% csrf_token %}
I would suggest reading template system explanation for programmers, it is very well written.

Related

'render' object has no attribute 'GET'

I'm working on a web application for a uni project using django and postgresql. This is my first time working with django forms and when trying to render any of them for a test run and to figure out the views the render fails with the above error message.
I have worked with Django beforehand but this is my first time working with forms -previously, I'd done object creation and edits through API views. I can't find where my code is wrong, but I've tried rewording it, moving lines around to see if it helps (it hasn't,) and even avoiding inheritance and trying to word it as a straightforward form (hasn't helped either.) I have four different forms but they all provide the same error message, so I'm just gonna show one user model extension that I'm not too confident about for an example, in case there's more wrong than I've realized.
This is the code I've got
class JdTform(UserCreationForm):
telefono = forms.IntegerField()
class Meta(UserCreationForm.Meta):
fields = [
'telefono'
]
labels = {
'telefono': 'teléfono'
}
widgets = {
'telefono': forms.NumberInput()
}
def jdt_form_view(request):
if request.method == 'GET':
form = JdTform()
return render(request, 'personas/formu_jdt.html', {'form': form})
if request.method == 'POST':
form = JdTform(request.POST)
if form.is_valid():
user = form.save()
fono = form.cleaned_data.get('telefono')
jdt = jefeDeTaller(telefono=fono, u=user)
jdt.save()
return redirect('cal_fecha')
<html lang="en">
<head>
<meta charset="utf-8">
<title>Gestor de Trabajo</title>
</head>
<body>
<header>
<h1>My Site</h1>
</header>
<main>
<h2>Sign up</h2>
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
</main>
</body>
</html>
urlpatterns = [
path('calendario/<int:ano>/<int:mes>/', views.calendario_mes, name='cal_fecha'),
path('usuarios/jefedetaller/', views.jdt_form_view, name='formulario_jdt'),
The error message I receive on the debug page is
AttributeError at /usuarios/jefedetaller/
'render' object has no attribute 'get'
with traceback
Request Method: GET
Request URL: http://127.0.0.1:8000/usuarios/jefedetaller/
Django Version: 2.2.1
Python Version: 3.5.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'gestor']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\Flavio\Envs\3dmente\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\Flavio\Envs\3dmente\lib\site-packages\django\utils\deprecation.py" in __call__
96. response = self.process_response(request, response)
File "C:\Users\Flavio\Envs\3dmente\lib\site-packages\django\middleware\clickjacking.py" in process_response
26. if response.get('X-Frame-Options') is not None:
Exception Type: AttributeError at /usuarios/jefedetaller/
Exception Value: 'render' object has no attribute 'get'
With this specific model, the idea is to create a user object, link it directly with a jdt object, and pass the fono information with this instantiation.
Thank you very much beforehand if you can help!

No CSRF token after Django 1.8 form error

I recently upgraded my website to Django 1.8 and am getting an "ImportError No module named lib" when my signup (user registration) form is posted. Specifically, if a user is signing up for an account and their passwords don't match, my form will display an error. If they then enter matching passwords, I get the following Django error:
Request Method: POST
Request URL: http://localhost:8000/create_account/
Django Version: 1.8.4
Python Version: 2.7.5
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'account',
'home',
'members',
'profile']
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Users/me/venv/scores/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
125. response = middleware_method(request, callback, callback_args, callback_kwargs)
File "/Users/me/venv/scores/lib/python2.7/site-packages/django/middleware/csrf.py" in process_view
189. return self._reject(request, REASON_BAD_TOKEN)
File "/Users/me/venv/scores/lib/python2.7/site-packages/django/middleware/csrf.py" in _reject
101. return _get_failure_view()(request, reason=reason)
File "/Users/me/venv/scores/lib/python2.7/site-packages/django/middleware/csrf.py" in _get_failure_view
33. return get_callable(settings.CSRF_FAILURE_VIEW)
File "/Users/me/venv/scores/lib/python2.7/site-packages/django/utils/lru_cache.py" in wrapper
101. result = user_function(*args, **kwds)
File "/Users/me/venv/scores/lib/python2.7/site-packages/django/core/urlresolvers.py" in get_callable
112. if submod and not module_has_submodule(import_module(parentmod), submod):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py" in import_module
37. __import__(name)
Exception Type: ImportError at /create_account/
Exception Value: No module named lib
As you can see from the stacktrace, when the form is posted with matching passwords, the response is being deemed invalid by the middleware before control is even returned to the create_account view that displayed the form. I set a breakpoint in the urlresolvers.py module and found that the module that can't be found is "lib.local_csrf". I should add that the form itself is composed of both a signin (authentication) form and the signup (registration) form in question and both forms contain csrf_token tags:
# home/templates/home.html
<form action="{% url 'sign-in' %}" method="post">
{% csrf_token %}
<!-- error fields appear here -->
{% for field in sign_in_form.visible_fields %}
{{ field.label_tag }}
{{ field }}
<input type="submit" value="Sign in">
Forgot password?
</form>
<form action="{% url 'create-account' %}" method="post">
{% csrf_token %}
<!-- error fields appear here -->
{% for field in create_account_form.visible_fields %}
{{ field.label_tag }}
{{ field }}
{% endfor %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<input type="submit" value="Sign up">
</form>
Here is the create_account view:
# account/views.py
def create_account(request, template):
# Initialize the signin form on the same page.
sign_in_form = SignInAuthenticationForm(request, label_suffix="")
if request.method == "POST":
create_account_form = CreateAccountForm(request.POST, label_suffix="")
if create_account_form.is_valid():
user = User.objects.create_user(
username = create_account_form.cleaned_data['username'],
password = create_account_form.cleaned_data['password1']
)
# Create a new account.
account = Account(user=user)
account.save()
# Do other stuff and then redirect user to next form
else:
create_account_form = CreateAccountForm(label_suffix="")
return render_to_response(template, locals())
What's most interesting is that when I set a breakpoint in the process_view in django.middleware.csrf, the csrf_token and request_csrf_token variables both contain the same value when the user initially submits the form with mismatched passwords. But when they enter matching passwords and resubmit the form a second time, the csrf_token contains the token value but request_csrf_token is blank. This was confirmed by the fact that request.POST['csrfmiddlewaretoken'] is not in the request.POST dictionary when the user resubmits the form. I don't understand why this is happening.
This form worked perfectly well in Django 1.6 but it's stopped working in 1.8 (or possibly 1.7). I looked through the 1.7 and 1.8 release notes and didn't see any changes to the CSRF functionality. I also read the template docs that pertain to CSRF and didn't see anything new there. Doing an online search on this error didn't turn up anything either.
I suspect that some of you will suggest that I use the django-registration-redux library. I don't think I can use it due to my registration workflow. You see, after the user registers on this form, they're redirected first to a page when they enter their user profile, then to a page where they can upload a photo, and then to a page to review and approve their profile and photo. After that, they're forwarded to my payment processor. They're only truly registered with a valid account if my payment processor tells me their payment method has been approved.
Thanks.
The actual error No module named lib appears to be because Django can't import the CSRF_FAILURE_VIEW you have specified in your settings. You could try removing it from your settings, then Django should show the default CSRF failure page instead of the error. I can't tell why the import is failing, because you haven't shown what CSRF_FAILURE_VIEW or your project structure is.
To fix the CSRF error, try using the render shortcut instead of render_to_response. It renders the template with a request context, so that the csrf_token tag works.
# avoid locals() if possible!
return render(request, template, {...})

Trying to send parameters

I'm trying to obtain dedicated urls of some products that I have in my shop.html page. I have five products that I named "cards": (Ysera, Neltharion, Nozdormu, Alexstrasza, Malygos). Each card should have a dedicated url (localhost:8000/card/1/, localhost:8000/card/2/, etc). but instead of obtaining that url, django launch me that message:
DoesNotExist at /card/1/ card matching query does not exist.
I imported properly the class model "card" in my views.py, in fact I am justly using card in a filter function to obtain all products in shop.html. please look my views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from dracoin.apps.synopticup.models import card
from dracoin.apps.home.forms import ContactForm,LoginForm
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth import login,logout,authenticate
from django.http import HttpResponseRedirect
def index(request):
return render_to_response('home/index.html',context_instance=RequestContext(request))
def landing(request):
return render_to_response('home/landing.html',context_instance=RequestContext(request))
def shop(request):
tarj = card.objects.filter(status=True)
ctx = {'tarjetas':tarj}
return render_to_response('home/shop.html',ctx,context_instance=RequestContext(request))
def singleCard(request,id_tarj):
tarj = card.objects.get(id=id_tarj)
ctx = {'card':tarj}
return render_to_response('home/singleCard.html',ctx,context_instance=RequestContext(request))
here my urls.py:
url(r'^card/(?P<id_tarj>.*)/$','dracoin.apps.home.views.singleCard',name='vista_single_card'),
My imported model:
class card(models.Model):
nombre = models.CharField(max_length=100)
descripcion = models.TextField(max_length=300)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.nombre
My singleCard.html:
{% extends 'base.html' %}
{% block title %} Tarjeta {{card.nombre}} {% endblock %}
{% block content %}
<h1>{{ card.nombre }}</h1><br>
<p> {{ card.descripcion }}</p>
{% endblock %}
I don't know if I have a wrong refering "card" class. But I try to apply other answers in this forum. For example:
In Django, how do I objects.get, but return None when nothing is found?
matching query does not exist Error in Django
Django error - matching query does not exist
I don't know if I commit a mistake applying these solutions. Including I try:
tarj = card.objects.filter(id=id_tarj)
Using this I obtain a blank page of my website...
apologizeme in advance my extensive question and if I overlook something.
Thanks!!
Answering to wolendranh I have an urls.py by app and the main urls.py.
Recently I'm learning django by my side and I can't understand how I can define my own consistent identifier in this case.
if it is still useful I put here a traceback generated with the error:
Environment:
Request Method: GET
Request URL: http://localhost:8000/card/1/
Django Version: 1.7
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dracoin.apps.synopticup',
'dracoin.apps.home')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/draicore/project/multilevel/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/draicore/project/dracoin/dracoin/apps/home/views.py" in singleCard
24. tarj = card.objects.get(id=id_tarj)
File "/home/draicore/project/multilevel/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
92. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/draicore/project/multilevel/local/lib/python2.7/site-packages/django/db/models/query.py" in get
357. self.model._meta.object_name)
Exception Type: DoesNotExist at /card/1/
Exception Value: card matching query does not exist.
excuse me for prolong this question.
As karthikr says in the comment, you don't have a card with id=1.
This is probably because you previously deleted and recreated a card. The id is an autoincrement field, which means the database does not reuse IDs that have been deleted. If you want your item to have a consistent identifier which you can always use to query it in the URL, you should probably define that as an explicit IntegerField (using another name than id), and query against that instead. Even better, use a slug rather than a numeric ID.
I have few things to clarify:
1. Do you have a single urls.py file in your project? or separate for every app.
If you have a separate like "your_project/card/urls" and it is included into main urls.py you should NOT use "card/" in your url. Because Django already knows that request is for that app.
r'^card/(?P<id_tarj>.*)/$' -> r'^(?P<id_tarj>.*)/$'
If it is in main urls.py try to replace:
r'^card/(?P<id_tarj>.*)/$'
to
r'^card/(?P\d+))/$'
P.s.: I don't have anough reputation for comments, so I added an answer. Sorry.

Django Type Error - render to string got multiple values for keyword argument context_instance

I'm new in django and I collect all the static and templates from the admin site to customize. Now I'm trying to render a queryset to the change_list.html from the admin site.
view.py
def person_list(request):
if request.method == 'GET':
qs = Person.objects.all()
return render(request, 'admin/change_list.html', {'app_label': 'clients'}, {'results_list':qs})
else:
return render(request, 'admin/change_list.html')
And I'm getting this type error:
render_to_string() got multiple values for keyword argument 'context_instance'
Here is the full traceback:
Environment:
Request Method: GET
Request URL: http://localhost:8000/clients/persons/
Django Version: 1.5.1
Python Version: 2.7.4
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'equipment',
'workers',
'clients',
'rents',
'bills',
'pays')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/facundo/dev/BLPServicios/blpservicios/clients/views.py" in persona_list
9. return render(request, 'admin/change_list.html', {'app_label': 'clients'}, {'results_list':qs})
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render
53. return HttpResponse(loader.render_to_string(*args, **kwargs),
Exception Type: TypeError at /clients/persons/
Exception Value: render_to_string() got multiple values for keyword argument 'context_instance'
Can you help me solve this? Thanks!
Try send values in one dictionary
{'app_label': 'clients', 'results_list':qs}
i think you are using the admin module to do something it can't... what are you trying to do?
i guess you'd better try to do it without the admin. often customizing it is more painful than implementing the code yourself, because of its complexity!
in particular, the {% result_list cl %} tag you see in the admin tamplate change_list.html (line 91) is not a template varible (that you are trying to pass in the context) but a template custom tag! whatever you want to do, this is the wrong path ;)

Django Messaging Framework not displaying message despite RequestContext

here's a conundrum for you,
Using Django 1.4, I cannot get messages set through the messages middleware to display in my templates. I have combed through the Django docs and ensured that my settings.py file referenced the relevant apps, context-processors and middleware. I have ensured that my view is rendering with the RequestContext instance. Yet, I still cannot get any of the messages to appear in the template.
settings.py:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
...
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.messages.context_processors.messages',
'tekextensions.context_processors.admin_media_prefix',
)
...
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin', #Admin interface
'django.contrib.admindocs', #Admin docs
...
My messages error_level is set to 20 (i.e. 'info' and above). I am using the default mappings.
views.py:
from django.contrib import messages
def index(request, *args, **kwargs):
#Do some funky jazz which works like build the timeline & page vars
...
messages.error = (request,"Horsey Bollox!")
messages.add_message = (request, messages.ERROR,"Why won't this f***ing thing work?") #Attempting alternate method
return render_to_response('funkyjazzdirectory/index.html',
{
'page': page,
'timeline': timeline,
},
context_instance=RequestContext(request))
template: (funkyjazzdirectory/index.html)
{% extends "base.html" %}
{% if messages.error %}
<div class="messages-errors">
Error:
<ul>
{% for msg in messages %}
<li>{{msg}}</li>
{% endfor %}
</ul>
</div>
{% endif %}
<p>
Other stuff such as iterating through {{timeline}} which renders absolutely fine
</p>
I have also tried substituting {{msg}} with:
<li>{{msg.message}}</li>
with no success.
The rest of the page outputs fine, Django does not throw an error. The console does not contain anything abnormal. The HTML code produced does not contain the div, nor the list tags anywhere. The template which this one extends (base.html) does not use the {{messages}} variable nor call a template tag which uses it.
I have tried passing the {{messages}} into a custom template tag for testing in the top of the index.html template. Here I can do:
def __init__(self, messages):
self.messages = messages
def render(self, context):
l = dir(context[self.messages])
print(l)
...which produces a list of methods / properties presumably of the message object. Yet, I cannot iterate over this at all, as "for m in messages:" does not run even once. Attempting to discover the size of this entity by:
print(len(context[self.messages]))
gives me nothing in the console.
The only time I've got it to actually output anything was when I manually passed the messages object into the template within the render_to_response tag then iterated over messages.error ({% for msg in messages.error %}) which produced two bullet points in the correct div: the first being filled with what looks like a var dump: ", POST:, COOKIES:{'csrftoken':"... the second bullet point containing just the last error message: "Why won't this f***ing thing work?". (Obviously this was just a test and I have not kept messages in the dict passed via render_to_response as I know it should arrive in the template via the context)
So, where did I go wrong?
Why can I not see my error messages in my template? Why can I not even get the messages to appear in the console?
Any light someone smarter than me can shed would be extremely helpful!
You seem to use a very strange way to add a message:
messages.error = (request,"Horsey Bollox!")
messages.add_message = (request, messages.ERROR,"Why won't this f***ing thing work?")
The correct syntax is:
messages.error(request,"Horsey Bollox!")
messages.add_message(request, messages.ERROR,"Why won't this f***ing thing work?")
The settings and templates are however fine.