Ошибки не отображаются в шаблонах после пользовательской валидации
Я работаю над формой, в которой несколько полей ввода зависят друг от друга. Я реализовал пользовательскую валидацию и добавил к ней сообщения об ошибках, но, хотя пользовательская валидация работает, сообщения об ошибках не отображаются в шаблонах.
form.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',]
view.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})
template.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>
Помните, что я проверяю плавающие значения из полей выбора. Я попробовал несколько решений и предложений (закомментированный код в форме), но ни одно из них не показывает сообщения.