[英]Django: Change value in request.POST to 0 if empty
I have the following form: 我有以下表格:
When one of the tickets is empty, my form sends me an error with that every field is required, now I am trying to check if the form value is empty, if it's empty I want to change it to 0
, so form.is_valid()
can be true. 当其中一张票是空的时,我的表单发给我一个错误,每个字段都是必需的,现在我正在尝试检查表单值是否为空,如果它是空的我想将其更改为
0
,所以form.is_valid()
可以是真的。
The attached code doesn't work. 附加的代码不起作用。 It says
string index out of range
. 它表示
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")
It's not very clean to try to alter the post data. 试图改变帖子数据并不是很干净。 Instead, make the field optional in your form with
required=False
(or blank=True
in the model field) so that there aren't form errors when the field is missing. 相反,在表单中使用
required=False
(或模型字段中的blank=True
)使字段成为可选字段,以便在缺少字段时不会出现表单错误。
If it's a model form, you could set a default value on the field. 如果是模型表单,则可以在该字段上设置默认值。 Or, for a regular form you could override
clean_<fieldname>
and return 0
when the value isn't specified. 或者,对于常规表单,您可以覆盖
clean_<fieldname>
并在未指定值时返回0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.