简体   繁体   中英

How To Get Django Form To Validate Multiple Fields Together

I'm trying to write a clean method that validates whether 3 fields (percentages) add up to zero. I followed the django documentation and added the clean() method to my form class but Django still redirects after the form submits, indicating the is_valid() function passed successfully.

It seems like the clean method just be called by the Django is_valid() and not allow the form to submit...

Have checked out a similar answer but no luck.

forms.py

    class RequirementsForm(forms.ModelForm):

class Meta:
    model = Profile
    fields = ('cal_req', 
        'prot_bool', 
        'carb_bool', 
        'fat_bool', 
        'stf_bool', 
        'fib_bool', 
        'sug_bool', 
        'sod_bool', 
        'cho_bool',
        'clc_bool',
        'irn_bool',
        'vta_bool',
        'vtc_bool',
        'prot_perc',
        'carb_perc',
        'fat_perc',
        'stf_g_thr',
        'fib_g_req',
        'sug_g_thr',
        'sod_mg_thr',
        'cho_mg_thr',# must opt-in for dietary cholesterol reqs. But default is 300 / Decimal(2000)
        'clc_mg_req',
        'irn_mg_req',
        'vta_mcg_req',
        'vtc_mg_req' )

    def clean(self):

        cleaned_data = super().clean()

        prot_perc = cleaned_data.get('prot_perc')
        fat_perc = cleaned_data.get('fat_perc')
        carb_perc = cleaned_data.get('carb_perc')

        if sum([prot_perc, fat_perc, carb_perc]) != 1.0:
            raise forms.ValidationError(_('Macro percents must add up to 1!')_)

views.py

@login_required(login_url='/login/')
def questionaire(request):

prof, created = Profile.objects.get_or_create(user=request.user) # Careful, this clashes with the reciever in models.py
if created:
    prof.save()
if request.method=='POST': # Will post requirements form
    req_form = RequirementsForm(request.POST, instance=prof)
    if req_form.is_valid():
        req_form.save()
        return HttpResponseRedirect('/')
else:
    req_form = RequirementsForm(instance=prof)
    context={'req_form':req_form, 'prof':prof}
    return render(request, 'core/questionaire_form.html', context)

form.html

            </tr>
        <tr>
            <th class ='type_label' colspan=6>Macronutrients</th>
        </tr>
        <tr>
             <td class="bool_col"></td>
            <td class="nm_col">Protein</td>
             <td class="micro_input">  
                {{req_form.prot_perc}}
             </td>
             <td>%</td>
              <td><input  id="prot_g" ></input></td>
              <td>{{req_form.prot_perc.errors</td>
        </tr>
        <tr>
            <td class="bool_col"></td>
            <td class="nm_col">Fat</td>
            <td class="micro_input">  {{req_form.fat_perc}}</td>
            <td id="unit1">%</td>

            <td><input  id="fat_g" ></input></td>
            <td></td>
        </tr>
        <tr>
            <td class="bool_col"></td>
            <td class="nm_col">Carbohydrates</td>
            <td class="micro_input">   {{req_form.carb_perc}}</td>
            <td id="unit1">%</td>

            <td><input  id="carb_g"></input></td>
            <td></td>
        </tr>

This was a simple indent error. The clean function should have been indented directly below the class RequirementsForm

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