Django 1.9 unittest error for messages but i dont see the error for 1.10.4 and 1.8

寵の児 提交于 2019-12-25 09:35:03

问题


The test fails with the error in Django 1.9 env, but tests run perfectly well in 1.10.4 and 1.8. Can someone throw some light here !

Here is the error

add_message raise MessageFailure('You cannot add messages without installing ' MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware

Check https://travis-ci.org/invaana/Hydronium/builds/182190626 for complete errors

views.py

def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Operation Successful! This is demo. Im not sending any messages')
        else:
            form.errors
            messages.error(request, 'Message not sent, Please fix the errors!.' )
    else:
        form = ContactForm()
    return render(request, 'pages/contact.html', {'form': form})

tests.py

def test_contactform_valid(self):
    res = self.client.post(reverse('contact'), {'name':'Ravi','email':'rrmerugu@gmail.com', 'text': 'im good' })
    self.assertIn('Operation Successful', res.content)

def test_contactform_invalid(self):
    res = self.client.post(reverse('contact'), {'name':'Ravi','email':'rrmerugu@gmail.com', 'text': '' })
    self.assertIn('Message not sent', res.content)

回答1:


Apparently,

MIDDLEWARE_CLASSES is used in 1.9, 1.8

MIDDLEWARE is used in 1.10.4.

To make the middleware compatible for both, I used the following code in settings.py

MIDDLEWARE = MIDDLEWARE_CLASSES = [
    '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',
]


来源:https://stackoverflow.com/questions/41033222/django-1-9-unittest-error-for-messages-but-i-dont-see-the-error-for-1-10-4-and-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!