简体   繁体   中英

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.

The attached code doesn't work. It says 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM