NOT NULL constraint failed: myapp_auth_user.username

14 views Asked by At

Error Message Screenshot

Please guys I'm getting the error message NOT NULL constraint failed: blango_auth_user.username when trying to register a new user on the blog.

class BlangoUserManager(BaseUserManager):
    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError("Email must be set")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault("is_staff", False)
        extra_fields.setdefault("is_superuser", False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)

        if extra_fields.get("is_staff") is not True:
            raise ValueError("Superuser must have is_staff=True.")
        if extra_fields.get("is_superuser") is not True:
            raise ValueError("Superuser must have is_superuser=True.")

        return self._create_user(email, password, **extra_fields)


class User(AbstractUser):
    username = None
    email = models.EmailField(
            _("email address"),
            unique=True,
        )

    objects = BlangoUserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []

    def __str__(self):
      return self.email

The above is my custom user model in which I'm overriding the username field to set it to none since I want to use the email field as a unique identifier.

MEANWHILE, If I remove the username=None argument, I'll get the error message UNIQUE constraint failed: blango_auth_user.username as the image below shows

Unique constraint failed error

This is my registration form.py file for more detail...

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django_registration.forms import RegistrationForm

from blango_auth.models import User


class BlangoRegistrationForm(RegistrationForm):
    class Meta(RegistrationForm.Meta):
        model = User

    def __init__(self, *args, **kwargs):
        super(BlangoRegistrationForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.add_input(Submit("submit", "Register"))

Thank you so much. I await your expert answers.

I tried to change the username=None attribute in the models.py file but still not working. All other answers on stack overflow does not solve my issue.

0

There are 0 answers