![](/img/trans.png)
[英]django: request.POST key is empty if the choicefield value is not set
[英]Django: Change value in request.POST to 0 if empty
我有以下表格:
当其中一张票是空的时,我的表单发给我一个错误,每个字段都是必需的,现在我正在尝试检查表单值是否为空,如果它是空的我想将其更改为0
,所以form.is_valid()
可以是真的。
附加的代码不起作用。 它表示string index out of range
。
def reserve_ticket(request):
if request.method == 'POST':
quantities = request.POST.getlist('quantity')
for i in range(len(quantities)):
if not request.POST['quantity'][i]:
request.POST['quantity'][i] = 0
form = ReserveForm(request.POST)
if form.is_valid():
print("Hello world")
return HttpResponse("Hello world")
else:
return HttpResponse("Back to homepage")
试图改变帖子数据并不是很干净。 相反,在表单中使用required=False
(或模型字段中的blank=True
)使字段成为可选字段,以便在缺少字段时不会出现表单错误。
如果是模型表单,则可以在该字段上设置默认值。 或者,对于常规表单,您可以覆盖clean_<fieldname>
并在未指定值时返回0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.