Python django.contrib.messages.constants.ERROR Examples

The following are 30 code examples of django.contrib.messages.constants.ERROR(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.messages.constants , or try the search function .
Example #1
Source File: tests_OrgSetUserPermsView.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_OrgSetUserPermsViewLastAdminSeveralMembersRemoveItsPermsKO(self):
        julia = self.login("julia")
        julia_perms = Permission.objects.get(organization__slugname="les-amis-de-la-terre", user=julia)
        # Now let's try to remove admin rights from julia
        # It should fail in order to make it impossible to have an admin-less Organization
        data = {
            'can_modify_permissions': 'off',
        }
        self.assertEqual(julia_perms.can_modify_permissions, True)
        response = self.client.post(reverse("org_set_user_perms", kwargs={'orgslugname': 'les-amis-de-la-terre',
                                                                          'user_name': 'julia'}),
                                    data, follow=True)
        self.assertRedirects(response, reverse("org_edit_user_perms",
                                               kwargs={'orgslugname': 'les-amis-de-la-terre', 'user_name': 'julia'}))
        self.assertEqual(response.context['permissions'].can_modify_permissions, True)
        julia_perms.refresh_from_db()
        self.assertEquals(julia_perms.can_modify_permissions, True)
        messages = response.context['messages']
        self.assertGreaterEqual(len(messages), 1)
        ThereIsAnyError = False
        for msg in messages:
            if msg.level == constants.ERROR:
                ThereIsAnyError = True
        self.assertEquals(ThereIsAnyError, True) 
Example #2
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_json_encoder_decoder(self):
        """
        A complex nested data structure containing Message
        instances is properly encoded/decoded by the custom JSON
        encoder/decoder classes.
        """
        messages = [
            {
                'message': Message(constants.INFO, 'Test message'),
                'message_list': [
                    Message(constants.INFO, 'message %s') for x in range(5)
                ] + [{'another-message': Message(constants.ERROR, 'error')}],
            },
            Message(constants.INFO, 'message %s'),
        ]
        encoder = MessageEncoder(separators=(',', ':'))
        value = encoder.encode(messages)
        decoded_messages = json.loads(value, cls=MessageDecoder)
        self.assertEqual(messages, decoded_messages) 
Example #3
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_enrollments_bad_response(self):
        """Verify a message is logged, and a separate message displayed to the user,
        if the API does not return HTTTP 200."""
        api_status = 500
        self.mock_enrollment_api(status=api_status)

        with LogCapture(LOGGER_NAME) as logger:
            response = self.load_view()
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.context['enrollments'], [])
            self.assert_message_equals(response, 'Failed to retrieve enrollment data.', MSG.ERROR)
            logger.check((
                LOGGER_NAME,
                'WARNING',
                'Failed to retrieve enrollments for [{}]. Enrollment API returned status code [{}].'.format(
                    self.user.username,
                    api_status
                )
            )) 
Example #4
Source File: tests.py    From ecommerce with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_create_refund_error(self):
        """Verify the view does not create a Refund if the selected Lines have already been refunded."""
        refund = self.create_refund()
        order = refund.order

        for line in order.lines.all():
            self.assertTrue(line.refund_lines.exists())

        # No new refunds should be created
        self.assertEqual(Refund.objects.count(), 1)
        response = self._request_refund(order)
        self.assertEqual(Refund.objects.count(), 1)

        # An error message should be displayed.
        self.assert_message_equals(response,
                                   'A refund cannot be created for these lines. They may have already been refunded.',
                                   MSG.ERROR) 
Example #5
Source File: admin.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def revoke_change(self, request, obj):
        if not self.has_change_permission(request, obj):
            raise PermissionDenied
        if obj.revoked:
            self.message_user(request, _('Certificate is already revoked.'), level=messages.ERROR)
            return HttpResponseRedirect(obj.admin_change_url)

        if request.method == 'POST':
            form = RevokeCertificateForm(request.POST, instance=obj)
            if form.is_valid():
                reason = form.cleaned_data['revoked_reason']
                if reason:
                    reason = ReasonFlags[reason]

                obj.revoke(
                    reason=reason,
                    compromised=form.cleaned_data['compromised'] or None
                )
                return HttpResponseRedirect(obj.admin_change_url)
        else:
            form = RevokeCertificateForm(instance=obj)

        context = dict(self.admin_site.each_context(request), form=form, object=obj, opts=obj._meta)
        return TemplateResponse(request, "admin/django_ca/certificate/revoke_form.html", context) 
Example #6
Source File: test_middleware.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handles_PowerActionAlreadyInProgress(self):
        request = factory.make_fake_request(factory.make_string(), "POST")
        error_message = (
            "Unable to execute power action: another action is "
            "already in progress for node %s" % factory.make_name("node")
        )
        error = PowerActionAlreadyInProgress(error_message)
        response = self.process_request(request, error)

        # The response is a redirect.
        self.assertEqual(request.path, extract_redirect(response))
        # An error message has been published.
        self.assertEqual(
            [(constants.ERROR, "Error: %s" % error_message, "")],
            request._messages.messages,
        ) 
Example #7
Source File: test_moderation.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_email_send_error(self, mock_fn):
        logging.disable(logging.CRITICAL)
        # Approve
        self.silent_submit()
        response = self.approve()
        logging.disable(logging.NOTSET)

        # An email that fails to send should return a message rather than crash the page
        self.assertEqual(response.status_code, 302)
        response = self.client.get(reverse('wagtailadmin_home'))

        # There should be one "approved" message and one "failed to send notifications"
        messages = list(response.context['messages'])
        self.assertEqual(len(messages), 2)
        self.assertEqual(messages[0].level, message_constants.SUCCESS)
        self.assertEqual(messages[1].level, message_constants.ERROR) 
Example #8
Source File: test_move_page.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_page_move_confirm(self):
        response = self.client.get(
            reverse('wagtailadmin_pages:move_confirm', args=(self.test_page_a.id, self.section_b.id))
        )
        self.assertEqual(response.status_code, 200)

        response = self.client.get(
            reverse('wagtailadmin_pages:move_confirm', args=(self.test_page_b.id, self.section_a.id))
        )
        # Duplicate slugs triggers a redirect with an error message.
        self.assertEqual(response.status_code, 302)

        response = self.client.get(reverse('wagtailadmin_home'))
        messages = list(response.context['messages'])
        self.assertEqual(len(messages), 1)
        self.assertEqual(messages[0].level, message_constants.ERROR)
        # Slug should be in error message.
        self.assertIn("{}".format(self.test_page_b.slug), messages[0].message) 
Example #9
Source File: test_middleware.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handles_NoConnectionsAvailable(self):
        request = factory.make_fake_request(factory.make_string(), "POST")
        error_message = (
            "No connections available for cluster %s"
            % factory.make_name("cluster")
        )
        error = NoConnectionsAvailable(error_message)
        response = self.process_request(request, error)

        # The response is a redirect.
        self.assertEqual(request.path, extract_redirect(response))
        # An error message has been published.
        self.assertEqual(
            [(constants.ERROR, "Error: " + error_message, "")],
            request._messages.messages,
        ) 
Example #10
Source File: test_cookie.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_json_encoder_decoder(self):
        """
        A complex nested data structure containing Message
        instances is properly encoded/decoded by the custom JSON
        encoder/decoder classes.
        """
        messages = [
            {
                'message': Message(constants.INFO, 'Test message'),
                'message_list': [
                    Message(constants.INFO, 'message %s') for x in range(5)
                ] + [{'another-message': Message(constants.ERROR, 'error')}],
            },
            Message(constants.INFO, 'message %s'),
        ]
        encoder = MessageEncoder(separators=(',', ':'))
        value = encoder.encode(messages)
        decoded_messages = json.loads(value, cls=MessageDecoder)
        self.assertEqual(messages, decoded_messages) 
Example #11
Source File: tests_OrgSetUserPermsView.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_OrgSetUserPermsViewSeveralAdminsRemoveItsPermsOK(self):
        julia = self.login("julia")
        julia_perms = Permission.objects.get(organization__slugname="alternatiba", user=julia)
        # Now let's try to remove admin rights from julia
        # It should fail in order to make it impossible to have an admin-less Organization
        data = {
            'can_modify_permissions': 'off',
        }
        self.assertEqual(julia_perms.can_modify_permissions, True)
        response = self.client.post(reverse("org_set_user_perms", kwargs={'orgslugname': 'alternatiba',
                                                                          'user_name': 'julia'}),
                                    data, follow=True)
        self.assertRedirects(response, reverse("org_edit_user_perms",
                                               kwargs={'orgslugname': 'alternatiba', 'user_name': 'julia'}))
        self.assertEqual(response.context['permissions'].can_modify_permissions, False)
        julia_perms.refresh_from_db()
        self.assertEquals(julia_perms.can_modify_permissions, False)
        messages = response.context['messages']
        self.assertGreaterEqual(len(messages), 1)
        ThereIsAnyError = False
        for msg in messages:
            if msg.level == constants.ERROR:
                ThereIsAnyError = True
        self.assertEquals(ThereIsAnyError, False) 
Example #12
Source File: tests_OrgSetUserPermsView.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_OrgSetUserPermsViewLastAdminRemoveItsPermsKO(self):
        julia = self.login("julia")
        julia_perms = Permission.objects.get(organization__slugname="rap", user=julia)
        # Now let's try to remove admin rights from julia
        # It should fail in order to make it impossible to have an admin-less Organization
        data = {
            'can_modify_permissions': 'off',
        }
        self.assertEqual(julia_perms.can_modify_permissions, True)
        response = self.client.post(reverse("org_set_user_perms", kwargs={'orgslugname': 'rap', 'user_name': 'julia'}),
                                    data, follow=True)
        self.assertRedirects(response, reverse("org_edit_user_perms",
                                               kwargs={'orgslugname': 'rap', 'user_name': 'julia'}))
        self.assertEqual(response.context['permissions'].can_modify_permissions, True)
        julia_perms.refresh_from_db()
        self.assertEquals(julia_perms.can_modify_permissions, True)
        messages = response.context['messages']
        self.assertGreaterEqual(len(messages), 1)
        ThereIsAnyError = False
        for msg in messages:
            if msg.level == constants.ERROR:
                ThereIsAnyError = True
        self.assertEquals(ThereIsAnyError, True) 
Example #13
Source File: tests_SignatureViews.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_show_signatures_post_resendallOK_org(self):
        self.login("julia")
        org = Organization.objects.get(name="Les Amis de la Terre")
        petition = org.petition_set.first()
        pid = petition.id
        signature = Signature.objects.create(
            first_name="Me",
            last_name="You",
            email="you@example.org",
            petition=petition)
        #sid = signature.id
        data = {
            'action': 're-send-all',
        }
        response = self.client.post(reverse("show_signatures", args=[pid]), data, follow=True)
        self.assertRedirects(response, reverse("show_signatures", args=[pid]))
        self.assertTemplateUsed(response, "petition/signature_data.html")
        messages = response.context['messages']
        self.assertGreaterEqual(len(messages), 1)
        ThereIsAnyError = False
        for msg in messages:
            if msg.level == constants.ERROR:
                ThereIsAnyError = True
        self.assertEquals(ThereIsAnyError, False) 
Example #14
Source File: tests_SignatureViews.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_show_signatures_post_resendallOK(self):
        julia = self.login("julia")
        petition = julia.petition_set.first()
        pid = petition.id
        signature = Signature.objects.create(
            first_name="Me",
            last_name="You",
            email="you@example.org",
            petition=petition)
        #sid = signature.id
        data = {
            'action': 're-send-all',
        }
        response = self.client.post(reverse("show_signatures", args=[pid]), data, follow=True)
        self.assertRedirects(response, reverse("show_signatures", args=[pid]))
        self.assertTemplateUsed(response, "petition/signature_data.html")
        messages = response.context['messages']
        self.assertGreaterEqual(len(messages), 1)
        ThereIsAnyError = False
        for msg in messages:
            if msg.level == constants.ERROR:
                ThereIsAnyError = True
        self.assertEquals(ThereIsAnyError, False) 
Example #15
Source File: tests_SignatureViews.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_show_signatures_post_resendOK_org(self):
        self.login("julia")
        org = Organization.objects.get(name="Les Amis de la Terre")
        petition = org.petition_set.first()
        pid = petition.id
        signature = Signature.objects.create(
            first_name="Me",
            last_name="You",
            email="you@example.org",
            petition=petition)
        sid = signature.id
        data = {
            'action': 're-send',
            'signature_id': [sid],
        }
        response = self.client.post(reverse("show_signatures", args=[pid]), data, follow=True)
        self.assertRedirects(response, reverse("show_signatures", args=[pid]))
        self.assertTemplateUsed(response, "petition/signature_data.html")
        messages = response.context['messages']
        self.assertGreaterEqual(len(messages), 1)
        ThereIsAnyError = False
        for msg in messages:
            if msg.level == constants.ERROR:
                ThereIsAnyError = True
        self.assertEquals(ThereIsAnyError, False) 
Example #16
Source File: test_middleware.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_no_connections_available_has_usable_cluster_name_in_msg(self):
        # If a NoConnectionsAvailable exception carries a reference to
        # the cluster UUID, RPCErrorsMiddleware will look up the
        # cluster's name and make the error message it displays more
        # useful.
        request = factory.make_fake_request(factory.make_string(), "POST")
        rack_controller = factory.make_RackController()
        error = NoConnectionsAvailable(
            factory.make_name("msg"), uuid=rack_controller.system_id
        )
        self.process_request(request, error)

        expected_error_message = (
            "Error: Unable to connect to rack controller '%s' (%s); no "
            "connections available."
            % (rack_controller.hostname, rack_controller.system_id)
        )
        self.assertEqual(
            [(constants.ERROR, expected_error_message, "")],
            request._messages.messages,
        ) 
Example #17
Source File: tests.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_error(self):
        messages.error(self.user, "Hello")
        self.assertMessageOk(constants.ERROR) 
Example #18
Source File: base.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_level_messages(storage):
    """
    Add 6 messages from different levels (including a custom one) to a storage
    instance.
    """
    storage.add(constants.INFO, 'A generic info message')
    storage.add(29, 'Some custom level')
    storage.add(constants.DEBUG, 'A debugging message', extra_tags='extra-tag')
    storage.add(constants.WARNING, 'A warning')
    storage.add(constants.ERROR, 'An error')
    storage.add(constants.SUCCESS, 'This was a triumph.') 
Example #19
Source File: base.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_level_messages(storage):
    """
    Add 6 messages from different levels (including a custom one) to a storage
    instance.
    """
    storage.add(constants.INFO, 'A generic info message')
    storage.add(29, 'Some custom level')
    storage.add(constants.DEBUG, 'A debugging message', extra_tags='extra-tag')
    storage.add(constants.WARNING, 'A warning')
    storage.add(constants.ERROR, 'An error')
    storage.add(constants.SUCCESS, 'This was a triumph.') 
Example #20
Source File: messages.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def error(user, message):
    """
    Adds a message with the ``ERROR`` level.

    :param user: User instance
    :param message: Message to show
    """
    message_user(user, message, constants.ERROR) 
Example #21
Source File: background_messages.py    From feedsubs with MIT License 5 votes vote down vote up
def error(user, message):
    """
    Adds a message with the ``ERROR`` level.

    :param user: User instance
    :param message: Message to show
    """
    message_user(user, message, constants.ERROR) 
Example #22
Source File: utils.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def error(self, msg):
        self.add_message(constants.ERROR, msg) 
Example #23
Source File: messages.py    From avos with Apache License 2.0 5 votes vote down vote up
def error(request, message, extra_tags='', fail_silently=False):
    """Adds a message with the ``ERROR`` level."""
    add_message(request, constants.ERROR, message, extra_tags=extra_tags,
                fail_silently=fail_silently) 
Example #24
Source File: test_middleware.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_handles_TimeoutError(self):
        request = factory.make_fake_request(factory.make_string(), "POST")
        error_message = "Here, have a picture of Queen Victoria!"
        error = TimeoutError(error_message)
        response = self.process_request(request, error)

        # The response is a redirect.
        self.assertEqual(request.path, extract_redirect(response))
        # An error message has been published.
        self.assertEqual(
            [(constants.ERROR, "Error: " + error_message, "")],
            request._messages.messages,
        ) 
Example #25
Source File: base_tags.py    From jorvik with GNU General Public License v3.0 5 votes vote down vote up
def level_to_bootstrap(message):
    map = {
        constants.DEBUG: 'alert-info',
        constants.INFO: 'alert-info',
        constants.SUCCESS: 'alert-success',
        constants.WARNING: 'alert-warning',
        constants.ERROR: 'alert-danger',
    }
    return map.get(message.level, 'alert-info') 
Example #26
Source File: form_views.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def form_invalid(self, form, msg=None, msg_level=None, **kwargs):
        msg_level = msg_level or constants.ERROR
        msg = msg or self.get_message(msg_level)
        add_message(self.request, msg_level, msg)
        return self.render_to_response(self.get_context_data(form=form, msg=msg, msg_level=msg_level, **kwargs)) 
Example #27
Source File: api.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def error(request, message, extra_tags='', fail_silently=False):
    """
    Adds a message with the ``ERROR`` level.
    """
    add_message(request, constants.ERROR, message, extra_tags=extra_tags,
                fail_silently=fail_silently) 
Example #28
Source File: extra_filters.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def message_icon(msg):
    """
        Returns the string class name of a message icon
        which feeds directly into Patternfly.
    """
    icons = {
        messages.ERROR: 'error-circle-o',
        messages.WARNING: 'warning-triangle-o',
        messages.SUCCESS: 'ok',
        messages.INFO: 'info',
    }
    return 'pficon-' + icons[msg.level] 
Example #29
Source File: test_view.py    From edx-enterprise with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_post_enrollment_error_bad_error_string(
            self,
            forms_client,
            views_client,
            course_catalog_client,
            reverse_mock,
            logging_mock,
    ):
        reverse_mock.return_value = '/courses/course-v1:HarvardX+CoolScience+2016'
        catalog_instance = course_catalog_client.return_value
        catalog_instance.get_course_run.return_value = {
            "name": "Cool Science",
            "start": "2017-01-01T12:00:00Z",
        }
        views_instance = views_client.return_value
        views_instance.enroll_user_in_course.side_effect = HttpClientError(
            "Client Error", content='This is not JSON'.encode()
        )
        forms_instance = forms_client.return_value
        forms_instance.get_course_details.side_effect = fake_enrollment_api.get_course_details
        user = UserFactory(id=2)
        course_id = "course-v1:HarvardX+CoolScience+2016"
        mode = "verified"
        response = self._enroll_user_request(user, mode, course_id=course_id)
        logging_mock.assert_called_with(
            'Error while enrolling user %(user)s: %(message)s',
            {'user': user.username, 'message': 'No error message provided'}
        )
        self._assert_django_messages(response, set([
            (messages.ERROR, "The following learners could not be enrolled in {}: {}".format(course_id, user.email)),
        ])) 
Example #30
Source File: test_view.py    From edx-enterprise with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_post_enrollment_error(
            self,
            forms_client,
            views_client,
            course_catalog_client,
            reverse_mock,
    ):
        reverse_mock.return_value = '/courses/course-v1:HarvardX+CoolScience+2016'
        catalog_instance = course_catalog_client.return_value
        catalog_instance.get_course_run.return_value = {
            "name": "Cool Science",
            "start": "2017-01-01T12:00:00Z",
        }
        views_instance = views_client.return_value
        views_instance.enroll_user_in_course.side_effect = HttpClientError(
            "Client Error", content=json.dumps({"message": "test"}).encode()
        )
        forms_instance = forms_client.return_value
        forms_instance.get_course_details.side_effect = fake_enrollment_api.get_course_details
        user = UserFactory(id=2)
        course_id = "course-v1:HarvardX+CoolScience+2016"
        mode = "verified"
        response = self._enroll_user_request(user, mode, course_id=course_id)
        self._assert_django_messages(response, set([
            (messages.ERROR, "The following learners could not be enrolled in {}: {}".format(course_id, user.email)),
        ]))