python 如何使用 HTTP 重定向传递信息(在 Django 中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/599280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass information using an HTTP redirect (in Django)
提问by user72389
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.
更新模型后,我想重定向到另一个页面,并且我希望此页面上出现诸如“字段X已成功更新”之类的消息。
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?
如何将此消息“传递”到另一个页面?HttpResponseRedirect 只接受一个URL。我以前在其他网站上看到过这样做。这是如何实现的?
回答by S.Lott
This is a built-in feature of Django, called "messages"
这是 Django 的一个内置功能,称为“消息”
See http://docs.djangoproject.com/en/dev/topics/auth/#messages
请参阅http://docs.djangoproject.com/en/dev/topics/auth/#messages
From the documentation:
从文档:
A message is associated with a User. There's no concept of expiration or timestamps.
Messages are used by the Django admin after successful actions. For example, "The poll Foo was created successfully." is a message.
消息与用户相关联。没有过期或时间戳的概念。
成功操作后,Django 管理员使用消息。例如,“投票 Foo 已成功创建”。是一条消息。
回答by user20955
You can use django-flashcookie app http://bitbucket.org/offline/django-flashcookie/wiki/Home
您可以使用 django-flashcookie 应用程序 http://bitbucket.org/offline/django-flashcookie/wiki/Home
it can send multiple messages and have unlimited types of messages. Lets say you want one message type for warning and one for error messages, you can write
它可以发送多条消息并且具有无限类型的消息。假设您想要一种用于警告的消息类型和一种用于错误消息的消息类型,您可以编写
def simple_action(request):
...
request.flash['notice'] = 'Hello World'
return HttpResponseRedirect("/")
or
或者
def simple_action(request):
...
request.flash['error'] = 'something wrong'
return HttpResponseRedirect("/")
or
或者
def simple_action(request):
...
request.flash['notice'] = 'Hello World'
request.flash['error'] = 'something wrong'
return HttpResponseRedirect("/")
or even
甚至
def simple_action(request):
...
request.flash['notice'] = 'Hello World'
request.flash['notice'] = 'Hello World 2'
request.flash['error'] = 'something wrong'
request.flash['error'] = 'something wrong 2'
return HttpResponseRedirect("/")
and then in you template show it with
然后在你的模板中显示它
{% for message in flash.notice %}
{{ message }}
{% endfor }}
or
或者
{% for message in flash.notice %}
{{ message }}
{% endfor }}
{% for message in flash.error %}
{{ message }}
{% endfor }}
回答by idbill
I liked the idea of using the message framework, but the example in the django documentation doesn't work for me in the context of the question above.
我喜欢使用消息框架的想法,但是在上述问题的上下文中,django 文档中的示例对我不起作用。
What really annoys me, is the line in the django docs:
真正让我烦恼的是 django 文档中的一行:
If you're using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context.
If you're using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context.
which is incomprehensible to a newbie (like me) and needs to expanded upon, preferably with what those 2 options look like.
这对于新手(如我)来说是不可理解的,需要扩展,最好是这两个选项的样子。
I was only able to find solutions that required rendering with RequestContext... which doesn't answer the question above.
我只能找到需要使用 RequestContext 进行渲染的解决方案...它没有回答上述问题。
I believe I've created a solution for the 2nd option below:
我相信我已经为下面的第二个选项创建了一个解决方案:
Hopefully this will help someone else.
希望这会帮助别人。
== urls.py ==
== urls.py ==
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns('',
(r'^$', main_page, { 'template_name': 'main_page.html', }, 'main_page'),
(r'^test/$', test ),
== viewtest.py ==
== viewtest.py ==
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
def test(request):
messages.success( request, 'Test successful' )
return HttpResponseRedirect( reverse('main_page') )
== viewmain.py ==
== 查看main.py ==
from django.contrib.messages import get_messages
from django.shortcuts import render_to_response
def main_page(request, template_name ):
# create dictionary of items to be passed to the template
c = { messages': get_messages( request ) }
# render page
return render_to_response( template_name, c, )
== main_page.html ==
== main_page.html ==
{% block content %}
{% if messages %}
<div>
{% for message in messages %}
<h2 class="{{message.tag}}">{{ message.message }}</h2>
{% endfor %}
</div>
{% endif %}
{% endblock %}
回答by Jan Detlefsen
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.
我已阅读并检查了所有答案,在我看来,现在要走的路是使用消息传递框架。一些回复相当陈旧,在发布时可能是正确的方式。
回答by Pydev UA
There is a lot of solutions
有很多解决方案
1 Use Django-trunk version - it support sending messages to Anonymous Users
1 使用 Django-trunk 版本 - 它支持向匿名用户发送消息
2 Sessions
2 节
def view1(request):
request.session['message'] = 'Hello view2!'
return HttpResponseRedirect('/view2/')
def view2(request):
return HttpResponse(request.session['message'])
3 redirect with param
3 使用参数重定向
return HttpResponseRedirect('/view2/?message=Hello+view2')
4 Cookies
4 饼干
回答by Ry4an Brase
Can you just pass the message as a query param oon the URL to which you're redirecting? It's not terribly RESTy, but it ought to work:
您可以将消息作为查询参数传递到您要重定向到的 URL 上吗?它不是非常 RESTy,但它应该可以工作:
return HttpResponseRedirect('/polls/%s/results/?message=Updated" % p.id)
and have that view check for a message param, scrub it for nasties, and display it at the top.
并让该视图检查消息参数,将其清理干净,并将其显示在顶部。
回答by Tony Joseph
I think this code should work for you
我认为这段代码应该适合你
request.user.message_set.create(message="This is some message")
return http.HttpResponseRedirect('/url')
回答by Revil
The solution used by Pydev UA is the less intrusive and can be used without modifying almost nothing in your code. When you pass the message, you can update your context in the view that handles the message and in your template you can show it.
Pydev UA 使用的解决方案侵入性较小,可以在不修改代码中几乎任何内容的情况下使用。传递消息时,您可以在处理消息的视图中更新上下文,并在模板中显示它。
I used the same approach, but instead passing a simple text, passed a dict with the information in useful fields for me. Then in the view, updated context as well and then returned the rendered template with the updated context.
我使用了相同的方法,但不是传递一个简单的文本,而是传递一个 dict,其中包含对我有用的字段中的信息。然后在视图中,更新上下文,然后返回带有更新上下文的渲染模板。
Simple, effective and very unobstrusive.
简单、有效且非常不引人注目。
回答by Geradeausanwalt
You could also have the redirect url be the path to an already parameterized view.
您还可以将重定向 url 设为已参数化视图的路径。
urls.py:
网址.py:
(r'^some/path/(?P<field_name>\w+)/$', direct_to_template,
{'template': 'field_updated_message.html',
},
'url-name'
),
views.py:
视图.py:
HttpResponseRedirect( reverse('url-name', args=(myfieldname,)) )
Note that args= needs to take a tuple.
请注意, args= 需要采用元组。
回答by Liorsion
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.
虽然到目前为止所有建议都有效,但我建议使用 Ry4an(在请求 URL 中传递它) - 只需将实际文本更改为预定义文本消息集中的编码文本。
Two advantages here:
这里有两个优点:
- Less chance of something hacking through your scrubbing of bad content
- 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.
其他与 cookie 相关的方法.. 好吧,如果浏览器不支持 cookie,它们将不起作用,并且稍微贵一些.. 但只是稍微贵一点。它们确实更干净。