Django 自定義 error_messages={} 返回錯誤資訊
阿新 • • 發佈:2020-10-27
Considerations regarding model’serror_messages
¶
Error messages defined at theformfield
level or at theform Metalevel always take precedence over the error messages defined at themodelfield
level.
Error messages defined onmodelfields
are only used when theValidationError
is raised during themodel validation step and no corresponding error messages are defined at the form level.
#您可以通過將NON_FIELD_ERRORS鍵新增到ModelForm的內部Meta類的error_messages字典中來覆蓋模型驗證所引起的NON_FIELD_ERRORS錯誤訊息:
You can override the error messages fromNON_FIELD_ERRORS
raised by model validation by adding theNON_FIELD_ERRORS
key to theerror_messages
ModelForm
’s innerMeta
class:
from django.core.exceptions import NON_FIELD_ERRORS
from django.forms import ModelForm
class ArticleForm(ModelForm):
class Meta:
error_messages = {
NON_FIELD_ERRORS: {
'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
}
}