首页 > 解决方案 > 自定义验证后,错误不会显示在模板中

问题描述

我正在研究一种很少有字段输入相互依赖的表单。我实现了自定义验证并向其添加了错误消息,但是,尽管自定义验证有效,但错误消息不会显示在模板中。

表格.py

class NewCalculationForm(forms.ModelForm):
 
    def clean(self):
        cleaned_data = super(NewCalculationForm, self).clean()
        if self.cleaned_data.get('Tsrcin') <= self.cleaned_data.get('Tsrcout'):
            raise forms.ValidationError({"Tsrcout": "Source outlet temperature has to be lower than inlet temperature."})
            # msg = "Source outlet temperature has to be lower than inlet temperature."
            # self.errors["Tsrcout"] = self.error_class([msg])    
        if self.cleaned_data.get('Tsinkin') >= self.cleaned_data.get('Tsinkout'):
            raise forms.ValidationError({"Tsinkout": "Sink outlet temperature has to be higher than inlet temperature."})
            # msg = "Sink outlet temperature has to be higher than inlet temperature."
            # self.errors["Tsinkout"] = self.error_class([msg])    
        return cleaned_data

    class Meta:
        model = Calculation
        fields = ['Tsrcin', 'Tsrcout', 'Qsrc','Tsinkin','Tsinkout',]

视图.py

def index(request):
    
    if request.method == 'POST':
        form = NewCalculationForm(request.POST or None)
        if form.is_valid():
            Tsrcin = form.cleaned_data.get("Tsrcin")
            Tsrcout = form.cleaned_data.get("Tsrcout")
            Qsrc = form.cleaned_data.get("Qsrc")
            Tsinkin = form.cleaned_data.get("Tsinkin")
            Tsinkout = form.cleaned_data.get("Tsinkout")
            [Pnet, Pel, thermaleff, savepath] = cycle_simulation(Tsrcin, Tsrcout, Qsrc, Tsinkin, Tsinkout)
            file1 = DjangoFile(open(os.path.join(savepath, "TSDiagrammORCCycle.png"), mode='rb'),name='PNG')           
            file2 = DjangoFile(open(os.path.join(savepath, "TQDiagrammORCCycle.png"), mode='rb'),name='PNG')
            instance = Calculation.objects.create(userid = request.user,Tsrcin = Tsrcin, Tsrcout = Tsrcout,\
                                           Qsrc = Qsrc, Tsinkin = Tsinkin, Tsinkout = Tsinkout, Pel = Pel,\
                                           time_calculated = datetime.today(), result = Pnet,\
                                           thermaleff = thermaleff, result_ts = file1, result_tq = file2)
            
            messages.success(request, "Calculation perfomed sucessfully!" )
            return HttpResponseRedirect(reverse('calculation-detail', kwargs={'slug': instance.slug}))
        else:
            #messages.error(request, "Values you entered are incorect. Please enter valid values." )
            form = NewCalculationForm()
    else:
        form = NewCalculationForm()
        
    return render(request, "index.html", context={"NewCalculationForm":form})

模板.html

<h5>In order to complete the calculation, please insert corresponding values.</h5>
        <form method="post">
            {% csrf_token %}
            {% if NewCalculationForm.errors %}
            {% for field in NewCalculationForm %}
                {% for error in field.errors %}
                    <div class="alert alert-danger">
                        <strong><span>{{ error|escape }}</strong>
                    </div>
                {% endfor %}
            {% endfor %}
            {% for error in NewCalculationForm.non_field_errors %}
                <div class="alert alert-danger">
                    <strong><span>{{ error|escape }}</strong>
                </div>
            {% endfor %}
        {% endif %}
            <table>
                <tr>
                    <td>Source inlet temperature {{NewCalculationForm.Tsrcin}} </td> 
                </tr>
                <tr>
                    <td>Source outlet temperature {{NewCalculationForm.Tsrcout}}</td> 
                </tr>
                <tr> 
                    <td>Source massflow {{NewCalculationForm.Qsrc}}</td> 
                </tr>
                <tr>
                    <td>Sink inlet temperature {{NewCalculationForm.Tsinkin}} </td> 
                </tr>
                <tr>
                    <td>Sink outlet temperature {{NewCalculationForm.Tsinkout}}</td>
                </tr>
            </table>
            <button class="btn btn-primary" type="submit"> Calculate </button>
        </form>

请记住,我正在验证选择字段中的浮点值。我尝试了几种解决方案和建议(表单中的注释代码),但没有一个显示消息。

标签: pythondjangodjango-viewsdjango-formsdjango-templates

解决方案


推荐阅读