How to pass information using an HTTP redirect (in

2019-03-09 19:30发布

I have a view that accepts a form submission and updates a model.

After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.

How can I "pass" this message to the other page? HttpResponseRedirect only accepts a URL. I've seen this done before on other sites. How is this accomplished?

11条回答
Evening l夕情丶
2楼-- · 2019-03-09 19:50

I have read and checked all answers, and it seems to me that the way to go now is using the messaging framework. Some of the replies are fairly old and have probably been the right way at the time of the posting.

查看更多
再贱就再见
3楼-- · 2019-03-09 19:50

While all suggestions so far work, I would suggest going with Ry4an's (pass it in the request URL) - just change the actual text to a coded text within a predefined set of text messages.

Two advantages here:

  1. Less chance of something hacking through your scrubbing of bad content
  2. You can localize your messages later if needed.

The other cookie related methods.. well, they don't work if the browser doesn't support cookies, and are slightly more expensive.. But only slightly. They're indeed cleaner to the eye.

查看更多
仙女界的扛把子
4楼-- · 2019-03-09 19:54

I think this code should work for you

request.user.message_set.create(message="This is some message")
return http.HttpResponseRedirect('/url')
查看更多
别忘想泡老子
5楼-- · 2019-03-09 19:54

You could also have the redirect url be the path to an already parameterized view.

urls.py:

(r'^some/path/(?P<field_name>\w+)/$', direct_to_template,
    {'template': 'field_updated_message.html',
    },
    'url-name'
),

views.py:

HttpResponseRedirect( reverse('url-name', args=(myfieldname,)) )

Note that args= needs to take a tuple.

查看更多
神经病院院长
6楼-- · 2019-03-09 19:57

There is a lot of solutions

1 Use Django-trunk version - it support sending messages to Anonymous Users

2 Sessions

def view1(request):
    request.session['message'] = 'Hello view2!'
    return HttpResponseRedirect('/view2/')


def view2(request):
    return HttpResponse(request.session['message'])

3 redirect with param

return HttpResponseRedirect('/view2/?message=Hello+view2')

4 Cookies

查看更多
登录 后发表回答