In Rails, flash is a way to display a message in the next page. It is
extremely useful to provide lightweight feedback to user operations.
For examples when the user, say, submits a new article and after
clicking on the "Submit" button, then is redirected to the front page,
you want to let him know that his submission was successful on the
front page.

What you would like to do is something like this:

...views.py
def new_article(request):
  ...
  article.save()
  flash("Your article was saved")
  ...
  HttpRedirect("frontpage")

I have implemented as a context processor:

Step 1:
create a file called session_context_processor.py:
def flash(request):
    # Add the flash message from the session and clear it
    flash = ""
    if 'flash' in request.session:
        flash = request.session['flash']
        del request.session['flash']
    return {'flash': flash}

Step 2:
Add the context processor to settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.auth',
    ...
    'session_context_processor.flash',
)

Step 3:
Add the context to *every* view that renders a template:
e.g. change:
    return render_to_response('mytemplate.html', context)
to:
    return render_to_response('mytemplate.html', context,
context_instance=RequestContext(request))
Again: do this in every view which should be displaying a flash (I
have it in all views)

Step 4:
Add the flash message to your base template:
...
... {{ flash }}
...

Step 5:
Set the flash whenever desired. Following the example above:
...views.py
def new_article(request):
  ...
  article.save()
  request.session['flash'] = "Your article was saved"
  ...
  HttpRedirect("frontpage")

That's it.

I've seen other pointers on how to do it but this one makes sense to
me.

One thing I want to add is a flash type to help the template format
the flash differently depending on whether it represents an error,
successful operation etc.

Suggestions for improvement are welcome.


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to