我在我的 django 管理员之一上启用了可编辑列表,以允许用户更新最小值和最大值。我已经设置了验证以确保最小值不大于最大值。验证按预期进行。但是,我对消息的显示方式不太满意。
因此,目前如屏幕截图所示,错误消息出现在字段的正上方,这扰乱了表格的对齐方式。有错误的列比其他列更宽,甚至没有用红色突出显示。
我想要实现的目标是在页面顶部显示错误,例如
Please correct the errors below.
Min value cannot be greater than max value
....
只需用红色边框突出显示错误字段即可。
实现这一目标的最佳方法是什么?
我尝试覆盖
is_valid
中的 CustomModelForm
函数,但我无法在那里添加消息,因为我无权访问 request
对象。我尝试传递请求对象的任何操作都是徒劳的。
class CustomModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__'
def is_valid(self):
if 'min_quantity' in self._errors:
# messages.error(self.request, self._errors["min_quantity"])
print("Handling a specific validation error for 'min'")
del self._errors['min_quantity']
super().is_valid()
一旦我能够设置 django 消息,我应该扩展什么模板来设置突出显示错误字段?
如果不是这个,我还能如何显示错误,以便眼睛更容易看到。
不要尝试直接在 is_valid() 方法中操作错误处理,而是考虑在表单的 clean() 方法中自定义验证,您可以在其中添加验证并更干净地处理错误。
示例:
from django import forms
from django.core.exceptions import ValidationError
class CustomModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__'
def clean(self):
cleaned_data = super().clean()
min_value = cleaned_data.get('min_value')
max_value = cleaned_data.get('max_value')
if min_value is not None and max_value is not None:
if min_value > max_value:
self.add_error('min_value', 'Min value cannot be greater than max value.')
self.add_error('max_value', 'Max value must be greater than min value.')
return cleaned_data