0

I have a view

class FooDetailView(View):
    def get(request, *args):
        foo_id = int(args[0])
        foo = Foo.objects.get(pk=foo_id)
        // do something and render the page

And now I would like to add some message into this page. For example

class FooFuncView(View):
    def get(request):
        // do something
        return redirect('foo-detail', foo_id, 'call Func successfully')

Since my urls.py is simply

url(r'^foo-detail/([1-9][0-9]*)/', FooDetailView.as_view(),
  name='foo-detail'),

I get the error message becuase no reverse match

Reverse for 'foo-detail' with arguments '(<id>, 'call Func successfully')' not found. 1 pattern(s) tried: ['tournament-detail/contestant/([1-9][0-9]*)/']

But I dont want the message shown in the url because it could be too long. I just want to simply render the page as FooDetailView does, and add extra message after different operation. It there any good way to achieve this? If not, any explantions for that?

2
  • 4
    Consider using the messages framework instead of trying to pass messages through URL parameters. Commented Dec 14, 2017 at 12:12
  • Oh you're trying to pass in a second param. Use django's messaging framework. You add messages to a user's session and the messages are automatically deleted once you read them. Commented Dec 14, 2017 at 12:15

2 Answers 2

2

When you return a redirect, you are simply telling the browser to go to the new url, e.g. /foo/1/. You can't include a message like 'call Func successfully' if it isn't part of the URL.

If you don't want to store the message (or a message code) in the URL, then you need to store it somewhere else, for example in the session.

Since this is a common requirement, Django includes the messages framework to do this.

Sign up to request clarification or add additional context in comments.

Comments

0

Using the already mentioned messages framework in your case:

from django.contrib import messages

class FooFuncView(View):
    def get(request):
        // do something
        messages.add_message(request, messages.SUCCESS, 'call Func successfully')
        return redirect('foo-detail', foo_id)

The text will be available in the template context of the page that is requested in the redirect.

From the documentation:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

If you are using django-bootstrap you can just add the following snippet into your base template:

{% load bootstrap3 %}

{# Display django.contrib.messages as Bootstrap alerts #}
{% bootstrap_messages %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.