VicaYang
VicaYang

Reputation: 554

Django redirect with non-URL parameter

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?

Upvotes: 0

Views: 594

Answers (2)

Risadinha
Risadinha

Reputation: 16666

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 %}

Upvotes: 0

Alasdair
Alasdair

Reputation: 308769

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.

Upvotes: 2

Related Questions