gpt4 book ai didi

验证失败时的Django表单字段初始值

转载 作者:行者123 更新时间:2023-12-04 09:22:10 27 4
gpt4 key购买 nike

提交表单但验证失败后,如何设置字段元素的值?例如

if form.is_valid():
form.save()
else:
form.data['my_field'] = 'some different data'

我真的不想把它放在 View 中,而是希望将它作为表单类的一部分。

谢谢

最佳答案

documentation说:

If you have a bound Form instance and want to change the data somehow, or if you want to bind an unbound Form instance to some data, create another Form instance. There is no way to change data in a Form instance. Once a Form instance has been created, you should consider its data immutable, whether it has data or not.



我真的不敢相信你的代码有效。但是没问题。根据文档,我会这样做:
if request.method == 'POST':
data = request.POST.copy()
form = MyForm(data)
if form.is_valid():
form.save()
else:
data['myField'] = 'some different data'
form = MyForm(initial=data)

关于验证失败时的Django表单字段初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2432421/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com