On Wed, Nov 24, 2010 at 3:01 PM, Paul McLanahan <[email protected]> wrote:
> I need to call a function
> from a view that needs to be able to set messages and potentially set
> other cookies. I need the request object to set the messages, and the
> response to set the cookies. This is already confusing in my opinion
> as the messages framework potentially uses cookies, but that's beside
> the point. If I get the response then pass it to my function, any
> messages it sets will not be shown to the user on that response, but
> would instead be saved and shown to the user on the subsequent
> request.
Okay, I think we're narrowing in on things. Just so I'm clear, you've
got a view that sets a message towards the beginning and then displays
that message in the template *on the very same request*, yes?
So in essence you're doing something like::
def my_view(request):
set_some_messages(request)
response = render_to_response(...)
set_some_cookies(response)
return resp
But you'd like to collapse `set_some_messages()` and
`set_some_cookies()` into a single function, so something like::
def my_view(request):
response = render_to_response(...)
set_some_cookies_and_messages(request, response)
return response
Does that about some it up?
Because if so, the problem has nothing to do with cookies. It's
happening because the messages are being fetched in the template,
which you're rendering into a response "too early". This in fact has
nothing to do with the request/response cycle or anything, but just
with the fact that you're fetching messages from a template into a
response. But remember: you can get a response without rendering a
template, so you could do something like this::
def my_view(request):
response = HttpResponse()
set_some_cookies_and_messages(request, response)
response.write(render_to_string(...))
return response
render_to_response is a shortcut that collapses a bunch of steps for
the common case, but does so at the expense of inflexibility.
Jacob
PS: Oh, and BTW, the reason you're seeing this problem with messages,
specifically, is that messages really aren't designed to be produced
and consumed in the same view. The canonical use case for messages is
for use in the redirect-after-POST pattern::
def my_view(request):
form = MyForm(request.POST or None)
if form.is_valid():
form.save()
messages.add_message("It worked!")
return redirect('success')
...
If you're producing and consuming messages in the same request you
might want a different tool, or you'll need to work around the
assumptions that the messages framework makes.
--
You received this message because you are subscribed to the Google Groups
"Django developers" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-developers?hl=en.