Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django messages middleware issue while testing post request

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.

like image 342
Emilio Conte Avatar asked Apr 25 '19 06:04

Emilio Conte


People also ask

What are messages in Django how it's helping Django application development?

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).

How do you use contrib messages in Django?

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."

How do you delete Django messages?

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.


1 Answers

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)
like image 65
Emilio Conte Avatar answered Sep 23 '22 06:09

Emilio Conte