I came up with a simple (and all too obvious) way to send error messages to the template. I am sure that there are better ways to do this. If you know of any, please take a minute to share them.
First, the Rails snippet.
- def index
- ...
- begin
- army = Army.find(params[:army][:id])
- rescue StandardError => se
- flash[:notice] = "Vare, legiones redde!"
- return
- end
- ...
- end
- from django.shortcuts import render_to_response
- def index(request):
- ...
- try:
- army = Army.objects.get(id = request.POST["army"])
- except ( KeyError, Army.DoesNotExist ):
- return render_to_response( "some_template.html", { "flash" : "Vare, legiones redde!" } )
- ...
- ...
- <% if @flash[:notice] -%>
- <div id="flash">
- <div><%= @flash[:notice] %></div>
- </div>
- <% end -%>
- ...
- ...
- {% if flash %}
- <div id="flash">
- <div>{{ flash }}</div>
- </div>
- {% endif %}
- ...
4 comments:
Unfortunately, flash in Rails works not only for forwards to the template, but also across a 302 redirect.
You are probably much happier with
request.user.message_set.create(message='Your Message goes here')
Thanks. I will remember to use user.message_set in the future.
There is a better way.
You can place you messages in session.
For example, request.session['message']
Then in templates just get it from request.session.message
You'll have to use middleware which will empty request.session['message'] in the beginning of all requests.
If you want to set message for the next page after redirect then you can use request.session['next_message'] and special middleware which will convert 'next_mesage' to 'message' in the beginning of all requests.
Post a Comment