1. 程式人生 > 實用技巧 >Django 自定義 error_messages={} 返回錯誤資訊

Django 自定義 error_messages={} 返回錯誤資訊

Considerations regarding model’serror_messages

Error messages defined at theformfieldlevel or at theform Metalevel always take precedence over the error messages defined at themodelfieldlevel.

Error messages defined onmodelfieldsare only used when theValidationErroris 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_ERRORSraised by model validation by adding theNON_FIELD_ERRORSkey to theerror_messages

dictionary of theModelForm’s innerMetaclass:

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.",
            }
        }