使用没有Java脚本和验证的POST向表单集中添加其他表单 [英] Add an additional form to a formset using POST without Javascript and validation

查看:78
本文介绍了使用没有Java脚本和验证的POST向表单集中添加其他表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Django表单集,但是使用纯服务器渲染,并且不需要Javascript向其添加其他表单。用户只需单击页面上的一个按钮,页面就会重新加载表单集中的其他表单。所有用户输入都应保留!视图中的相关部分是:

I want to use a Django formset, but with pure server rendering and without the need of Javascript to add additional forms to it. The user should just click a button on the page and the page should reload with an additional form in the formset. All user input should be preserved! The relevant part in the view is:

if request.POST.get('add_form') == "true":
  cp = request.POST.copy()
  cp['form-TOTAL_FORMS'] = int(cp['form-TOTAL_FORMS']) + 1
  fs = MyFormSet(cp)

问题在于,当 MyFormSet(cp)呈现表单表示形式时,会添加验证错误(例如「此栏位为必填」)。这是丑陋的,不能接受的。我该如何呈现它而不会出现错误(它们应该只在提交整个表单时出现)?

The problem is that when MyFormSet(cp) renders a form representation it adds validation errors to it (like "This field is required"). This is ugly and not acceptable. How can I render it without the errors (they should only be present when the whole form was submitted)?

MyFormSet(initial = ...)似乎不是一个选择,因为它也必须在 UpdateView 中工作(文档非常清楚,初始仅用于其他形式),并且POST数据也不能直接用作初始值。

MyFormSet(initial=...) seems not to be an option as it must also work in a UpdateView (the docs are pretty clear that initial is only for extra forms) and also the POST data can't be directly used as initial values.

我非常感谢任何提示,因为它花了我几个小时而无处可寻(这似乎是一个通用功能,因为Django的其余部分与Javascript无关)。

I am super thankful for any hint as it took me several hours without getting anywhere (and it seems to be such a common feature as the rest of Django is so Javascript agnostic).

推荐答案

hack,但这可以(在初始化表单集之后):

It feels like a hack, but this works (after the formset was initialized):

fs._errors = {}
for form in fs:
  form._errors = {}

在将其呈现为HTML时,将从字段中删除所有错误。背景是当 _errors 设置为 None (默认值)时,表单在呈现时会进行自我验证。当将其设置为空字典时,表单将不再对其自身进行验证,而仅思考表单。没有任何错误。因此不会显示任何错误消息。

This removes all errors from the fields when it is rendered to HTML. The background is that when _errors is set to None (the default) the form validates itself when it is rendered. When it is set to an empty dict the form will not validate itself anymore and just "thinks" that there are no errors in it. So no error messages are rendered.

这篇关于使用没有Java脚本和验证的POST向表单集中添加其他表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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