[Answer]-Django: Combining field error message

1👍

You should inherit UserCreationForm from forms.Form instead of forms.ModelForm, define in it email/password fields with required=False and check both fields in clean() method.

Something like this:

class UserCreationForm(forms.Form):

    email = forms.EmailField(required=False)
    password = forms.CharField(required=False, widget=forms.PasswordInput)

    def clean(self):
        email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')
        if not (email and password):
            raise forms.ValidationError(
                             'email and password fields cannot be left blank')

    def save(self, commit=True):
        user = User(email=self.cleaned_data['email'])
        user.set_password(self.cleaned_data['password'])
        if commit:
            user.save()
        return user

0👍

You can write a Model.clean for your model

class MyCustomUser(AbstractBaseUser):
    usermail = models.EMailField(.......)

    def clean(self):
        if not self.usermail and not self.password:
            raise ValidationError({'usermail': 'Mail address and Password are required!'})

This will raise a validation error pointing your usermail field.

👤Mp0int

Leave a comment