Question

I created a model like this

class Users(models.Model):
    alpha_field = RegexValidator(regex=r'^[a-zA-Z]+$', message='Name can only contain letters')
    username = models.SlugField(max_length=50, unique=True)
    first_name = models.CharField(max_length=50, verbose_name='first Name', validators=[alpha_field])
    last_name = models.CharField(max_length=50, validators=[alpha_field])
    password = models.SlugField(max_length=50)

and I made a form out of it and I want to raise my own error messages.

class UsersForm(forms.ModelForm):

class Meta:
    model = Users
    widgets = {'password':forms.PasswordInput()}

def __init__(self, *args, **kwargs):
    super( UsersForm, self ).__init__(*args, **kwargs)
    self.fields[ 'username' ].widget.attrs[ 'placeholder' ]="Username"
    self.fields[ 'first_name' ].widget.attrs[ 'placeholder' ]="First Name"  
    self.fields[ 'last_name' ].widget.attrs[ 'placeholder' ]="Last Name"
    self.fields[ 'password' ].widget.attrs[ 'placeholder' ]="Password"
    self.fields['first_name'].label='first Name'
    self.fields['first_name'].error_messages = {'required': 'First Name is Required'}

as you can see, I already created the error message if the first_name field was not filled out. However, I know that the CharField can raise a lot more error messages (for example, if submitted first_name is greater than the max_length). I want to have a custom error message for each and every possible error message which can be raised. Is there a place where I can see a list of all the possible error messages which a CharField form can raise?

Also, my verbose name in first_name is not working, if I can get the verbose name to work than I wouldn't need to create a custom message for the error messages. Note that I did already create a thread about the verbose_name not working and I still haven't figured out the exact reason as to why it isn't working. If the verbose_name can start working, that would be great. Here is a link to the thread:

django verbose_name not working

Was it helpful?

Solution

Here is the documentation on all the default error message keys for each field: https://docs.djangoproject.com/en/dev/ref/forms/fields/#built-in-field-classes Maybe try googling next time?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top