如何自定义“用户名已存在”消息?

时间:2017-12-05 02:58:18

标签: django

我的forms.py有自定义用户创建类...

class RegisterForm(UserCreationForm):
 error_messages= {
  "password_mismatch": _("Passwords do not match."),
 }

为了澄清,当用户尝试使用已存在的用户名注册时,我不知道哪个error_messages密钥对应于一个Django吐出的密钥。当用户选择已存在的用户名时,我需要替换哪条错误消息?

1 个答案:

答案 0 :(得分:0)

也许覆盖clean_username()方法并提供你自己的error_message:

error_messages= {

"password_mismatch": _("Passwords do not match."),

"username_exists": _("Username already present`")}



def clean_username(self):
    username = self.cleaned_data.get("username")

    try:
        User._default_manager.get(username=username)
        #if the user exists, then let's raise an error message

        raise forms.ValidationError( 
          self.error_messages['username_exists'],  #my error message

          code='username_exists',   #set the error message key

            )
    except User.DoesNotExist:
        return username # if user does not exist so we can continue the registration process