【问题标题】:django - redisplay a form after postback but as unbounddjango - 回发后重新显示表单但未绑定
【发布时间】:2011-12-19 06:54:26
【问题描述】:

对 python 和 django 还是很陌生,虽然正在学习 ;-)

我有一个旨在显示包含联系信息的表单的视图。成功处理表单并保存/创建对象后,我想再次显示相同的视图(以添加另一个联系人),但添加了一条消息,说明之前的联系人信息已成功保存。

从Django return redirect() with parameters我了解到,通过传递参数重定向到视图的方法是再次调用视图并显示响应。

我的观点开始如下:

def addabentry(request, entrytype, messages=[]):
""" Presents form to create a company listing, then enters company into database"""

回发并成功保存数据后,我再次调用视图如下:

messages = ["%s %s has been added." % (entrytype, entry.name)]
response = addabentry(request, entrytype=entrytype, messages=messages)
return HttpResponse(response)

但是,第二轮的表单似乎和之前的数据绑定了,大概是因为POST参数还在我传递给视图的请求对象中。

有没有办法第二次取消绑定表单?或者,更有可能的是,有没有更好的方法来做我想做的事?我需要使用引用的 SO 问题中提到的 request.sessions 吗?

感谢您的帮助!

W.

【问题讨论】:

    标签: django forms


    【解决方案1】:

    你需要messages 框架。

    【讨论】:

    • 是的,也许还有一些表单允许在页面上动态加载多个联系人表单(可能使用 javascript):docs.djangoproject.com/en/dev/topics/forms/formsets
    • 谢谢!还将查看消息/会话
    • 在对消息框架进行了更多研究之后,它似乎确实是一个更好的解决方案。已相应地更改了接受的答案。谢谢!
    【解决方案2】:

    我认为您可能使事情变得比他们需要的复杂得多。

    来自the docs中的基本表单示例

    def contact(request):
        message = ''
        if request.method == 'POST': # If the form has been submitted...
            form = ContactForm(request.POST) # A form bound to the POST data
            if form.is_valid(): # All validation rules pass
                # Process the data in form.cleaned_data
                # ...
                # instead of redirecting here, create a new blank form, and add a message
                form = ContactForm()
                message = "contact successfully created"
        else:
            form = ContactForm() # An unbound form
    
        return render_to_response('contact.html', {
            'form': form,
            'message': message,
        })
    

    【讨论】:

    • 天哪。这很明显(现在它指出了!)。谢谢!
    • @Westerley 是的,如果你想重新发明轮子,那就太好了。
    • 消息框架非常适合跨多个页面的消息(例如重定向后)。由于这种情况保持在同一页面上,因此使用消息框架可能会过大
    • @second 什么是矫枉过正?将消息存储在 cookie 中?
    • @second 顺便说一句,使用 POST 表单而不重定向成功并不是一个好主意。
    猜你喜欢
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2020-01-23
    • 2017-10-11
    • 1970-01-01
    相关资源
    最近更新 更多