Home > OS >  Django User Manager Not Checking Model Validators
Django User Manager Not Checking Model Validators

Time:12-02

I'm using a custom django user model. I have created everything and all seems perfect until I try to call the create_user from a registration page on the template. It is creating the user without taking the validators I have placed in the models into consideration. The validators are working just fine until I try to use the create_user action.

def validate_reg(value):
    try:
        x = SignUpAccess.objects.get(reg_key=value)
        if x.is_used == True:
            raise ValidationError(
                message='Your validation number is used already',
            )
    except SignUpAccess.DoesNotExist:
        raise ValidationError(
            message='Your validation number does not exist',
        )


class User(AbstractUser):
    username = None
    email = models.EmailField(
        unique=True,
        max_length=75,
        # db_index=True,
        primary_key=True,
        verbose_name='email address'
    )
    reg_number = models.CharField(
        max_length=12,
        unique=True,
        null=True,
        validators=[validate_reg]
    )
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    date_joined = models.DateTimeField(default=timezone.now)

    REQUIRED_FIELDS = []
    USERNAME_FIELD = 'email'

    objects = UserManager()

As seen above I have added a validator in the registration number to make sure only those with a valid registration number can create an account on the site. This works perfectly when I try to create a user from admin (which is really pointless).

As with custom user models, I have a user manager

class UserManager(BaseUserManager):
    def create_user(self, email, first_name, last_name, reg_number, password=None):
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            first_name=first_name,
            last_name=last_name,
            reg_number=reg_number,
        )

        user.set_password(password)
        user.save()
        return user

Everything should work fine until I try to create a user on my registration view,

def register_user(request):
    user = User
    if request.method == "POST":
        email = request.POST['email']
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        reg_number = request.POST['reg_number']
        password = request.POST['password']
        user.objects.create_user(
            email,
            first_name,
            last_name,
            reg_number,
            password=password,
        )

Calling the create user, while testing it on the template, typing an invalid registration number still creates a user with an invalid registration number, and this shouldn't work because the model itself has a validator on the registration field that should stop it. It looks as though the create_user manager is by-passing the validator, please help.

CodePudding user response:

have you tried full clean?

class MyModle(models.Model):

    def save(self, *args, **kwargs):
        try:
            self.full_clean()
            super(MyModle, self).save(*args, **kwargs)
        except IntegrityError:
            raise ValidationError("error message")
  • Related