djangodjango-formsmodelformnotnull

NOT NULL constraint failed: accounts_myuser.password


I am doing a web application in django where users can create accounts. I'm storing the users' passwords in plaintext as authentication in my system does not totally depend on password but also on the otp. The problem I'm facing all of a sudden(it worked fine earlier) at the POST request of registration, is "NOT NULL constraint failed: accounts_myuser.password". I tried deleting database and migrations and re-migrated but it didn't help. I'm giving the ModelForm and the Model(custom one) below.I've only two fields namely 'email' and 'username' described in my model. It worked fine and I could register users successfully earlier with the code below. Could anyone please help me?

forms.py

class UserCreationForm(forms.ModelForm):

    password1 = forms.IntegerField(label='Password', min_value=0000, max_value=9999, widget=forms.PasswordInput)

    password2 = forms.IntegerField(label='Password Confirmation', min_value=0000, max_value=9999,
                                   widget=forms.PasswordInput)


    class Meta:
        model = User
        fields = ['username', 'email']

    def clean_password1(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords do not match!")
        if len(str(password1)) != 4 or len(str(password2)) != 4:
            raise forms.ValidationError("Passwords should be of length Four!")
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.password = self.cleaned_data['password1']

        if commit:
            user.save()
        return user

models.py

class MyUserManager(BaseUserManager):

    def create_user(self, username, email, password=None):

        if not email:

            raise ValueError('Users must have an email')

        user = self.model(
                    username = username,
                    email = self.normalize_email(email),
                    password = password
                )

        # user.set_password(password)

        user.save(using=self._db)

        return user


    def create_superuser(self, username, email, password=None):
        user = self.create_user(
                username, email, password
                )
        user.is_admin = True
        user.is_staff = True
        user.set_password(password)
        user.save(using=self._db)
        return user

Solution

  • When you call the methods create_user or create_superuser, are you passing valid values for the password keyword?

    Because, if you pass a null password (None) to any of the two method, this would definitely throw a "NOT NULL constraint failed" error on the passwerod field.