Python django.contrib.messages.get_messages() Examples

The following are 30 code examples of django.contrib.messages.get_messages(). 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 , or try the search function .
Example #1
Source File: test_views_tag.py    From django-flexible-subscriptions with GNU General Public License v3.0 6 votes vote down vote up
def test_tag_create_create_and_success(admin_client):
    """Tests that tag creation and success message works as expected."""
    tag_count = models.PlanTag.objects.all().count()

    response = admin_client.post(
        reverse('dfs_tag_create'),
        {'tag': '1'},
        follow=True,
    )

    messages = list(get_messages(response.wsgi_request))

    assert models.PlanTag.objects.all().count() == tag_count + 1
    assert messages[0].tags == 'success'
    assert messages[0].message == 'Tag successfully added'


# TagUpdateView
# ----------------------------------------------------------------------------- 
Example #2
Source File: base.py    From c3nav with Apache License 2.0 6 votes vote down vote up
def call_api_hybrid_view_for_api(func, request, *args, **kwargs):
    response = func(request, *args, **kwargs)
    if isinstance(response, APIHybridResponse):
        result = OrderedDict(response.get_api_response(request))

        messages = []
        for message in get_messages(request):
            messages.append({
                'level': DEFAULT_MESSAGE_TAGS[message.level],
                'message': message.message
            })
        if messages:
            result['messages'] = messages
            result.move_to_end('messages', last=False)

        api_response = APIResponse(result, status=response.status_code)
        if request.method == 'GET':
            response.add_headers(api_response)
        return api_response
    elif isinstance(response, HttpResponse) and response.status_code in (304, 412):
        # 304 Not Modified, 412 Precondition Failed
        return response
    raise NoAPIHybridResponse 
Example #3
Source File: test_views_subscription.py    From django-flexible-subscriptions with GNU General Public License v3.0 6 votes vote down vote up
def test_subscription_delete_and_success(admin_client, django_user_model):
    """Tests for success message on successful deletion."""
    user = django_user_model.objects.create_user(username='a', password='b')
    cost = create_cost(plan=create_plan())
    subscription = create_subscription(user, cost)
    subscription_count = models.UserSubscription.objects.all().count()

    response = admin_client.post(
        reverse(
            'dfs_subscription_delete',
            kwargs={'subscription_id': subscription.id}
        ),
        follow=True,
    )

    messages = list(get_messages(response.wsgi_request))

    assert models.UserSubscription.objects.all().count() == (
        subscription_count - 1
    )
    assert messages[0].tags == 'success'
    assert messages[0].message == 'User subscription successfully deleted' 
Example #4
Source File: test_views_subscribe.py    From django-flexible-subscriptions with GNU General Public License v3.0 6 votes vote down vote up
def test_cancel_post_updates_instance(client, dfs):
    """Tests that POST request properly updates subscription instance."""
    subscription = dfs.subscription
    subscription_id = subscription.id

    client.force_login(dfs.user)
    response = client.post(
        reverse(
            'dfs_subscribe_cancel', kwargs={'subscription_id': subscription_id}
        ),
        follow=True
    )

    subscription = models.UserSubscription.objects.get(id=subscription_id)
    messages = list(get_messages(response.wsgi_request))

    assert subscription.date_billing_end == datetime(2018, 2, 1, 1, 1, 1)
    assert subscription.date_billing_next is None
    assert messages[0].tags == 'success'
    assert messages[0].message == 'Subscription successfully cancelled' 
Example #5
Source File: test_views.py    From django-simplestore with MIT License 6 votes vote down vote up
def test_updating_cart_item(self):
        session = self.client.session

        cart = self._create_testing_cart()
        cart.session_key = session.session_key
        cart.save()

        cart_item = self._create_testing_cart_item(cart_instance=cart, product_instance=self.test_product)

        response = self.client.post(reverse('cart:update', kwargs={'pk': cart_item.pk}),
            data={'cart_item_quantity': '2'}, follow=True
        )

        messages = [msg for msg in get_messages(response.wsgi_request)]

        updated_quantity = response.context['cart'].items.first().quantity
        cart_item.quantity = updated_quantity
        cart_item.save()

        self.assertEqual(response.status_code, 200)
        self.assertEqual(cart_item.quantity, 2)
        self.assertEqual(cart_item.total_price, Decimal(cart_item.quantity * cart_item.product.price))
        self.assertEqual(messages[0].tags, 'success', 'Message type should return success type')
        self.assertEqual(messages[0].message, 'Product quantity has been updated.') 
Example #6
Source File: test_views_plan_list_detail.py    From django-flexible-subscriptions with GNU General Public License v3.0 6 votes vote down vote up
def test_detail_delete_delete_and_success_message(admin_client):
    """Tests for success message on successful deletion."""
    plan_list = create_plan_list()
    detail = create_plan_list_detail(plan_list=plan_list)
    detail_count = models.PlanListDetail.objects.all().count()

    response = admin_client.post(
        reverse(
            'dfs_plan_list_detail_delete',
            kwargs={
                'plan_list_id': plan_list.id,
                'plan_list_detail_id': detail.id
            }
        ),
        follow=True,
    )

    messages = list(get_messages(response.wsgi_request))

    assert models.PlanListDetail.objects.all().count() == detail_count - 1
    assert messages[0].tags == 'success'
    assert messages[0].message == (
        'Subscription plan successfully removed from plan list'
    ) 
Example #7
Source File: test_views_plans.py    From django-flexible-subscriptions with GNU General Public License v3.0 6 votes vote down vote up
def test_plan_create_create_and_success(admin_client):
    """Tests that plan creation and success message works as expected."""
    plan_count = models.SubscriptionPlan.objects.all().count()

    post_data = {
        'plan_name': '1',
        'plan_description': 'a',
        'grace_period': 0,
        'costs-TOTAL_FORMS': '0',
        'costs-INITIAL_FORMS': '0',
        'costs-MIN_NUM_FORMS': '0',
        'costs-MAX_NUM_FORMS': '1000',
    }

    response = admin_client.post(
        reverse('dfs_plan_create'),
        post_data,
        follow=True,
    )

    messages = list(get_messages(response.wsgi_request))

    assert models.SubscriptionPlan.objects.all().count() == plan_count + 1
    assert messages[0].tags == 'success'
    assert messages[0].message == 'Subscription plan successfully added' 
Example #8
Source File: test_views_plan_list.py    From django-flexible-subscriptions with GNU General Public License v3.0 6 votes vote down vote up
def test_plan_list_update_update_and_success(admin_client):
    """Tests that plan list update and success message works as expected."""
    # Setup initial plan list for update
    plan_list = create_plan_list('1')
    plan_list_count = models.PlanList.objects.all().count()

    response = admin_client.post(
        reverse('dfs_plan_list_update', kwargs={'plan_list_id': plan_list.id}),
        {'title': '2'},
        follow=True,
    )

    messages = list(get_messages(response.wsgi_request))

    assert models.PlanList.objects.all().count() == plan_list_count
    assert models.PlanList.objects.get(id=plan_list.id).title == '2'
    assert messages[0].tags == 'success'
    assert messages[0].message == 'Plan list successfully updated'


# PlanListDeleteView
# ----------------------------------------------------------------------------- 
Example #9
Source File: test_views_plan_list.py    From django-flexible-subscriptions with GNU General Public License v3.0 6 votes vote down vote up
def test_plan_list_create_create_and_success(admin_client):
    """Tests that plan list creation and success message works as expected."""
    plan_list_count = models.PlanList.objects.all().count()

    response = admin_client.post(
        reverse('dfs_plan_list_create'),
        {'title': '1'},
        follow=True,
    )

    messages = list(get_messages(response.wsgi_request))

    assert models.PlanList.objects.all().count() == plan_list_count + 1
    assert messages[0].tags == 'success'
    assert messages[0].message == 'Plan list successfully added'


# PlanListUpdateView
# ----------------------------------------------------------------------------- 
Example #10
Source File: test_views_tag.py    From django-flexible-subscriptions with GNU General Public License v3.0 6 votes vote down vote up
def test_tag_update_update_and_success(admin_client):
    """Tests that tag update and success message works as expected."""
    # Setup initial tag for update
    tag = create_tag('1')
    tag_count = models.PlanTag.objects.all().count()

    response = admin_client.post(
        reverse('dfs_tag_update', kwargs={'tag_id': tag.id}),
        {'tag': '2'},
        follow=True,
    )

    messages = list(get_messages(response.wsgi_request))

    assert models.PlanTag.objects.all().count() == tag_count
    assert models.PlanTag.objects.get(id=tag.id).tag == '2'
    assert messages[0].tags == 'success'
    assert messages[0].message == 'Tag successfully updated'


# TagDeleteView
# ----------------------------------------------------------------------------- 
Example #11
Source File: __init__.py    From mitoc-trips with GNU General Public License v3.0 6 votes vote down vote up
def add_unique_message(self, level, message, **kwargs):
        """ Add a message, but only after first making sure it's not already been emitted.

        This helps guard against any message generator adding the same message
        multiple times before the next time the messages are displayed. Once messages
        are displayed, `used` is set on the storage object returned by
        `get_messages()` and the queue is cleared.

        Returns True if message was sent for the first time.
        """
        expected = Message(message=message, level=level, **kwargs)
        if any(msg == expected for msg in messages.get_messages(self.request)):
            return False

        messages.add_message(self.request, level, message, **kwargs)
        return True 
Example #12
Source File: tests.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def test_remove_all_from_grouping_filtered_by_sidereal(self):
        data = {
            'grouping': self.fake_grouping.id,
            'remove': True,
            'isSelectAll': 'True',
            'selected-target': [],
            'query_string': 'type=SIDEREAL&name=&key=&value=&targetlist__name=',
        }
        response = self.client.post(reverse('targets:add-remove-grouping'), data=data)
        self.assertEqual(self.fake_grouping.targets.count(), 0)
        messages = [(m.message, m.level) for m in get_messages(response.wsgi_request)]
        self.assertIn(('1 target(s) successfully removed from group \'{}\'.'.format(self.fake_grouping.name),
                       SUCCESS), messages)
        self.assertIn(('2 target(s) not in group \'{}\': {}'.format(
            self.fake_grouping.name, self.fake_targets[1].name + ', ' + self.fake_targets[2].name
        ), WARNING), messages) 
Example #13
Source File: tests.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def test_add_all_to_grouping_filtered_by_sidereal(self):
        data = {
            'grouping': self.fake_grouping.id,
            'add': True,
            'isSelectAll': 'True',
            'selected-target': [],
            'query_string': 'type=SIDEREAL&name=&key=&value=&targetlist__name=',
        }
        response = self.client.post(reverse('targets:add-remove-grouping'), data=data)
        self.assertEqual(self.fake_grouping.targets.count(), 3)
        messages = [(m.message, m.level) for m in get_messages(response.wsgi_request)]
        self.assertIn(('2 target(s) successfully added to group \'{}\'.'.format(self.fake_grouping.name),
                       SUCCESS), messages)
        self.assertIn((
            '1 target(s) already in group \'{}\': {}'.format(self.fake_grouping.name, self.fake_targets[0].name),
            WARNING), messages
        ) 
Example #14
Source File: tests.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def test_add_selected_to_grouping(self):
        data = {
            'grouping': self.fake_grouping.id,
            'add': True,
            'isSelectAll': 'False',
            'selected-target': [self.fake_targets[0].id, self.fake_targets[1].id],
            'query_string': '',
        }
        response = self.client.post(reverse('targets:add-remove-grouping'), data=data)

        self.assertEqual(self.fake_grouping.targets.count(), 2)
        self.assertTrue(self.fake_targets[0] in self.fake_grouping.targets.all())
        self.assertTrue(self.fake_targets[1] in self.fake_grouping.targets.all())

        messages = [(m.message, m.level) for m in get_messages(response.wsgi_request)]
        self.assertIn(('1 target(s) successfully added to group \'{}\'.'.format(self.fake_grouping.name),
                       SUCCESS), messages)
        self.assertIn(('1 target(s) already in group \'{}\': {}'.format(
            self.fake_grouping.name, self.fake_targets[0].name), WARNING), messages) 
Example #15
Source File: test_views_bootstrap_elasticsearch.py    From richie with MIT License 6 votes vote down vote up
def test_views_bootstrap_elasticsearch_with_permission(self, mock_command):
        """Confirm triggering the search index bootstrapping works as expected."""
        user = UserFactory(is_staff=True)
        self.client.login(username=user.username, password="password")

        # Add the necessary permission
        self.add_permission(user, "can_manage_elasticsearch")

        url = "/api/v1.0/bootstrap-elasticsearch/"
        response = self.client.post(url, follow=True)
        self.assertEqual(response.status_code, 200)
        content = json.loads(response.content)
        self.assertEqual(content, {})

        # Check the presence of a confirmation message
        messages = list(get_messages(response.wsgi_request))
        self.assertEqual(len(messages), 1)
        self.assertEqual(
            str(messages[0]), "The search index was successfully bootstrapped"
        )

        mock_command.assert_called_once_with("bootstrap_elasticsearch") 
Example #16
Source File: test_views.py    From Project-Dashboard-with-Django with MIT License 6 votes vote down vote up
def test_create_valid_user_success(self):
        """Test creating user with valid payload is successful"""

        payload = {
            "email": "test@gmail.com",
            "password1": "test@1234567",
            "password2": "test@1234567",
            "name": "Test name"
        }

        response = self.client.post(CREATE_USER_URL, payload)
        self.assertEqual(response.status_code, 302)
        user_exists = get_user_model().objects.filter(email=payload["email"]).exists()
        self.assertTrue(user_exists)
        user_profile_exists = MyProfile.objects.filter(owner__email="test@gmail.com").exists()
        self.assertTrue(user_profile_exists)
        self.assertEqual(response['Location'], "/")
        messages = list(get_messages(response.wsgi_request))
        self.assertEqual(str(messages[0]), "You have successfully registered") 
Example #17
Source File: test_views.py    From Project-Dashboard-with-Django with MIT License 6 votes vote down vote up
def test_login_valid_user_success(self):
        """Test login user with valid payload is successful"""

        payload = {
            "email": "test@gmail.com",
            "password": "test@1234567",
            "name": "Test name"
        }

        create_user(**payload)

        response = self.client.post(LOGIN_USER_URL, payload)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], "/")
        messages = list(get_messages(response.wsgi_request))
        self.assertEqual(str(messages[0]), "You have successfully logged in") 
Example #18
Source File: test_views.py    From Project-Dashboard-with-Django with MIT License 6 votes vote down vote up
def test_login_invalid_credentials_user(self):
        """Test login user with invalid credentials"""

        payload = {
            "email": "test@gmail.com",
            "password": "test@1234567",
            "name": "Test name"
        }

        payload_invalid = {
            "email": "invalid@gmail.com",
            "password": "test@1234567",
            "name": "Test name"
        }

        create_user(**payload)
        response = self.client.post(LOGIN_USER_URL, payload_invalid)
        self.assertEqual(response.status_code, 200)
        messages = list(get_messages(response.wsgi_request))
        self.assertEqual(str(messages[0]), "Incorrect username or password") 
Example #19
Source File: views.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def get_user_messages(request):
    from django.contrib.messages import get_messages

    themessages = get_messages(request)
    data = []

    for message in themessages:
        data.append({
            'text': message.message,
            'status': message.level_tag,
        })

    return JsonResponse({'messages': data}) 
Example #20
Source File: test_views.py    From django-simplestore with MIT License 5 votes vote down vote up
def test_deleting_cart_item(self):
        session = self.client.session

        cart = self._create_testing_cart()
        cart.session_key = session.session_key
        cart.save()

        cart_item = self._create_testing_cart_item(
            cart_instance=cart,
            product_instance=self.test_product
        )

        response = self.client.post(reverse('cart:remove',
            kwargs={'product_id': cart_item.product_id}),
            data={'product_id': cart_item.product_id}, follow=True)

        messages = [msg for msg in get_messages(response.wsgi_request)]

        self.assertEqual(response.status_code, 200)
        self.assertEqual(messages[0].tags,
            'success',
            'Message type should return success type'
        )
        self.assertEqual(
            messages[0].message,
            'The item has been deleted from your cart.',
            'Message text should be equal to: The item has been deleted from '
            'your cart')
        self.assertEqual(cart.items.count(), 0, 'Cart should have zero items.') 
Example #21
Source File: base.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def assertMessages(self, response, expected):
        messages = [str(m) for m in list(get_messages(response.wsgi_request))]
        self.assertEqual(messages, expected) 
Example #22
Source File: tests_unit.py    From django-bootstrap-modal-forms with MIT License 5 votes vote down vote up
def test_DeleteMessageMixin(self):
        """
        Delete object through BSModalDeleteView.
        """

        # Request to delete view passes message to the response
        response = self.client.post('/delete/1')
        messages = get_messages(response.wsgi_request)
        self.assertEqual(len(messages), 1) 
Example #23
Source File: test_views.py    From Project-Dashboard-with-Django with MIT License 5 votes vote down vote up
def test_logout_redirects(self):
        response = self.client.get(LOGOUT_USER_URL)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], "/")
        messages = list(get_messages(response.wsgi_request))
        self.assertEqual(str(messages[0]), "You have successfully logged out") 
Example #24
Source File: general.py    From django-htk with MIT License 5 votes vote down vote up
def clear_messages(request):
    # clear messages by iterating
    # https://docs.djangoproject.com/en/1.11/ref/contrib/messages/#expiration-of-messages
    storage = messages.get_messages(request)
    for message in storage:
        pass 
Example #25
Source File: message_utils.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def serialize(request):
    """
    Returns Django's flash messages serialized as a list of dicts.
    """
    return [
        _serialize_message(message)
        for message in get_messages(request)
    ] 
Example #26
Source File: test_views.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_error_message_from_request(self):
        return list(get_messages(self.request))[-1].message 
Example #27
Source File: test_templatetags.py    From edx-enterprise with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_alert_messages(self, alert_messages, expected_messages):
        """
        Test that the alert_messages template tag returns the correct message given a message type.
        """
        request = self._get_mock_request()
        self._add_messages(request, alert_messages)

        template = Template("{% load enterprise %} {% alert_messages messages %}")
        rendered = template.render(Context({'messages': messages.get_messages(request)}))

        for expected_icon, expected_message in expected_messages:
            assert expected_icon in rendered.strip()
            assert expected_message in rendered.strip() 
Example #28
Source File: test_messaging.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_django_messages_used(self):
        request = make_request()

        self.adapter_process(MESSAGES.UPDATE_LEAD, request=request)

        messages = list(get_messages(request))
        self.assertEqual(len(messages), 1)
        self.assertTrue(MESSAGES.UPDATE_LEAD.value in messages[0].message)
        self.assertTrue(self.adapter.adapter_type in messages[0].message) 
Example #29
Source File: api.py    From volontulo with MIT License 5 votes vote down vote up
def messages_view(request):
    """REST API view with Django messages."""
    return Response(
        serializers.MessageSerializer(get_messages(request), many=True).data,
        status=status.HTTP_200_OK
    ) 
Example #30
Source File: utils.py    From django-cas-server with GNU General Public License v3.0 5 votes vote down vote up
def json_response(request, data):
    """
        Wrapper dumping `data` to a json and sending it to the user with an HttpResponse

        :param django.http.HttpRequest request: The request object used to generate this response.
        :param dict data: The python dictionnary to return as a json
        :return: The content of ``data`` serialized in json
        :rtype: django.http.HttpResponse
    """
    data["messages"] = []
    for msg in messages.get_messages(request):
        data["messages"].append({'message': msg.message, 'level': msg.level_tag})
    return HttpResponse(json.dumps(data), content_type="application/json")