I'm trying to test an UpdateView that adds a message to the redirected success page. It seems my issue comes from messages
because of pytest returns:
django.contrib.messages.api.MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware
My test code is:
def test_authenticated_staff(self, rf):
langues = LanguageCatalog.objects.create(
lang_src='wz',
lang_dest='en',
percent='4'
)
req = rf.get(reverse("dashboard.staff:lang-update", kwargs={'pk': langues.pk}))
data = {'lang_src': 'it',
'lang_dest': 'en',
'percent': '34'}
req = rf.post(reverse(
"dashboard.staff:lang-update", kwargs={'pk': langues.pk}), data=data)
req.user = UserFactory()
resp = views.LangUpdateView.as_view()(req, pk=langues.pk)
I precise that the MessageMiddleware
is present in MIDDLEWARE
settings. I use Django==2.0.13
.
For this, Django provides full support for cookie- and session-based messaging, for both anonymous and authenticated users. The messages framework allows you to temporarily store messages in one request and retrieve them for display in a subsequent request (usually the next one).
Add a Django success messagecontrib at the top of the file then go to the view function where you wish to add the message(s). In this case, it's a contact view that needs a Django success message and a Django error message. Add a success message just before the return redirect ("main:homepage") stating "Message sent."
You need to iterate through the messages for your current set of messages as retrieved from the 'get_messages' method. You can use this code anywhere you want to clear the messages before setting new ones or where you want to simply clear all messages.
I found the solution. In order to test a such request, you need first to annotate it with a session and then a message. Actually it means to add these lines:
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
# in your test method:
"""Annotate a request object with a session"""
middleware = SessionMiddleware()
middleware.process_request(req)
req.session.save()
"""Annotate a request object with a messages"""
middleware = MessageMiddleware()
middleware.process_request(req)
req.session.save()
# and then (in my case)
resp = views.LangUpdateView.as_view()(req, pk=langues.pk)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With