ModelForm を使用してフォームを作成しています。一意のフィールドの検証という1つのことを除いて、すべて正常に機能します。コード:
class Article(models.Model):
...
title = models.CharField(max_length=255, unique=True, error_messages={'max_length' : 'max translation',
'unique' : 'unique translation',
'required' : 'req translation',})
...
class ArticleForm(ModelForm):
...
title = forms.CharField(max_length=255, min_length=3, error_messages={'required' : 'req translation',
'min_length' : 'min translation',
'max_length' : 'max translation',
'unique' : 'unique translation',})
しかし、一意でないタイトルでフォームを保存すると、カスタム翻訳エラーは表示されませんが、デフォルト エラーが表示されます。固有のフィールド エラーが表示されるのを修正するにはどうすればよいですか?
編集: それを行うための非常に便利な方法を見つけたと思います。多分誰かがそれを使うでしょう:)
def unique_error_message(self, model_class, unique_check):
if 'put_field_name_here' in unique_check and len(unique_check) == 1:
return 'Here goes a custom unique error'
return super(Article, self).unique_error_message(model_class, unique_check)