我可以从模型中更改基于类的视图的错误消息吗?以下内容不起作用,它始终会提供来自Django的默认消息。
型号:
class Child(models.Model):
name = models.CharField(max_length=100, error_messages={ 'blank': 'cannot be blank or null', 'null': 'cannot be blank or null',})
视图:
class ChildCreate(CreateView):
model = Child
fields = '__all__'
success_url = reverse_lazy('children-list')
答案 0 :(得分:1)
来自docs:
在表单字段级别或在Meta表单上定义的错误消息 级别始终优先于在 模型字段级别。
因此,您可以创建模型表单并在其中添加required
错误消息:
class ChildForm(forms.ModelForm):
use_required_attribute = False
class Meta:
model = models.Child
fields = '__all__'
error_messages = {'name': {'required': 'cannot be blank or null'}}
class ChildCreate(CreateView):
model = Child
form_class = forms.ChildForm
success_url = reverse_lazy('children-list')