如何使用上下文重定向Django? [英] How do I redirect in Django with context?

查看:116
本文介绍了如何使用上下文重定向Django?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个验证和保存表单的视图。表单保存后,我想重定向到一个list_object视图,并显示一条成功消息客户xyz的表单已成功更新...

I have a view that validates and saves a form. After the form is saved, I'd like redirect back to a list_object view with a success message "form for customer xyz was successfully updated..."

HttpResponseRedirect doesn'似乎它会工作,因为它只有一个参数的url,没有办法通过字典与它。

HttpResponseRedirect doesn't seem like it would work, because it only has an argument for the url, no way to pass dictionary with it.

我已经尝试修改我的包装器的object_list到将dict作为具有必要上下文的参数。我从保存表单的视图内返回对这个包装器的调用。但是,当页面呈现时,url是'/ customer_form /',而不是'/ list_customers /'。我尝试修改请求对象,然后将其传递给object_list包装器,但没有起作用。

I've tried modifying my wrapper for object_list to take a dict as a parameter that has the necessary context. I the return a call to this wrapper from inside the view that saves the form. However, when the page is rendered, the url is '/customer_form/' rather than '/list_customers/'. I tried modifying the request object, before passing it to the object_list wrapper, but that did not work.

谢谢。

推荐答案

请注意,这里建议的答案仅适用于Django< 1.2:

您是否可以控制重定向到的视图?在这种情况下,您可以将重定向之前的上下文保存在会话中。目标视图可以从会话中拾取上下文(并将其删除),并使用它来呈现模板。

Do you have control over the view that you are redirecting to? In that case you can save the context in the session before redirecting. The target view can pick up the context (and delete it) from the session and use it to render the template.

如果您的要求是显示一个消息,那么有一个更好的方法来做到这一点。您的第一个视图可以使用 auth 创建一条消息,并将第二个视图读取并删除。这样的东西:

If your only requirement is to display a message then there is a better way to do this. Your first view can create a message for the current using auth and have the second view read and delete it. Something like this:

def save_form(request, *args, **kwargs):
    # all goes well
    message = _("form for customer xyz was successfully updated...")
    request.user.message_set.create(message = message)
    return redirect('list_view')

def list_view(request, *args, **kwargs):
    # Render page

# Template for list_view:
{% for message in messages %}
   ... 
{% endfor %}

消息保存到数据库。这意味着即使重定向后您也可以访问它们。在渲染模板时,它们将被自动读取。您将不得不使用 RequestContext 使其正常工作。

Messages are saved to the database. This means that you can access them even after a redirect. They are automatically read and deleted on rendering the template. You will have to use RequestContext for this to work.

对于Django => 1.2阅读答案涉及邮件

这篇关于如何使用上下文重定向Django?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆