【问题标题】:How To Get Django Form To Validate Multiple Fields Together如何让 Django 表单同时验证多个字段
【发布时间】:2018-12-31 11:39:04
【问题描述】:

我正在尝试编写一个 clean 方法来验证 3 个字段(百分比)是否加起来为零。我跟着djangodocumentation把clean()方法加到了我的表单类中,但是表单提交后Django仍然重定向,说明is_valid()函数成功通过。

似乎 clean 方法只是被 Django is_valid() 调用并且不允许表单提交...

查看了类似的answer,但没有运气。

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>

【问题讨论】:

    标签: django validation django-forms


    【解决方案1】:

    这是一个简单的缩进错误。 clean 函数应该在 RequirementsForm 类下面直接缩进

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 2012-09-23
      • 2019-06-11
      • 2015-10-11
      • 2015-08-06
      相关资源
      最近更新 更多