0
  class CustomAccount(models.Model):
        user = models.OneToOneField("auth.User")
        role =  models.CharField(max_length = 50,   default = 'student',    choices=APPROVAL_CHOICES)
        balance = models.FloatField( default = 0 )
        timezone = models.CharField(max_length = 200)
        def __str__(self):

            return self.user.username +" ["+ self.role + "]"

    class CustomAccountForm(forms.ModelForm):
        username = forms.CharField(max_length=30 )
        email = forms.EmailField(max_length=255 )
        password1 = forms.CharField(label= "Password",widget=forms.PasswordInput())
        password2 = forms.CharField(label="Password confirmation", widget=forms.PasswordInput , help_text="Enter the same password as above, for verification.")    

        def save(self, commit= True):
            user = User.objects.create_user(username = self.cleaned_data['username'], email = self.cleaned_data['email'] , password = self.cleaned_data['password1'])
            user.save()
            self.user = user
            return super(CustomAccountForm, self).save(commit=commit)

        def clean_username(self):
            username = self.cleaned_data["username"]
            try:
                User.objects.get(username=username)
            except User.DoesNotExist:
                return username
            raise forms.ValidationError("A user with that username already exists.")

        def clean_password2(self):
            password1 = self.cleaned_data.get("password1", "")
            password2 = self.cleaned_data["password2"]
            if password1 != password2:
                raise forms.ValidationError("The two password fields didn't match.")
            return password2
        def clean_email(self):
            email = self.cleaned_data["email"]
            try:
                User.objects.get(email=email)
            except User.DoesNotExist:
                return email
            raise forms.ValidationError("A user with that emailaddress already exists.")    
        class Meta:
            model = CustomAccount       
            exclude = ['balance','user']

I want to create Custom account in Django Admin section using single form which has fields of auth.User and CustomAccount Model. I have getting error IntegrityError at /admin/mylogin/customaccount/add/ NOT NULL constraint failed: mylogin_customaccount.user_id

4
  • Do you have pre populated data in that customer account table? Commented Apr 21, 2016 at 10:11
  • Yes I have two objects Commented Apr 21, 2016 at 13:46
  • If user is foreign key i might have suggested you to add null=True in user field. As you are connecting OnetoOne field to User you cannot apply null=True, i would suggest you to delete the two records in DB and try to apply the migration Commented Apr 22, 2016 at 5:52
  • Best way to solve your problem is to define your own user model - docs.djangoproject.com/en/1.9/topics/auth/customizing/…
    – ssapkota
    Commented Apr 22, 2016 at 13:00

2 Answers 2

0

Since you are getting a not null error, I think you need to specify that the field is not required. Here is an example from one of my apps. This says that the form field is not required.

class arunModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        myuser = kwargs.pop('user', None)
        super(arunModelForm, self).__init__(*args, **kwargs)

        self.fields['nanoadded'].required = False
        self.fields['response'].required = False

I also include this in my models so that my model fields can be null, like this:

class arun(models.Model):
    auser = models.CharField(max_length=50, null=True)
    adate = models.DateField(null=True)
    atime = models.TimeField(null=True)

If I still get not null errors after I do both of these things, I fill the field with a place holder value to allow me to further investigate the problem.

1
  • what you said will be correct only if its a FK, you cannot have null=True to OnetoOne field Commented Apr 22, 2016 at 5:55
0

You have removed the user from the form and in the save method, you have assigned self.user in save method. So when saving the form, the user attribute is not used for CustomAccountForm and the user field for CustomAccount is None.

Your save method should look like:

def save(self, commit= True):
    user = User.objects.create_user(username =self.cleaned_data['username'], email = self.cleaned_data['email'] ,     password = self.cleaned_data['password1'])
    user.save()
    obj = super(CustomAccountForm, self).save(commit=False)
    obj.user = user
    obj.save()
4
  • Now I am getting UNIQUE constraint failed: mylogin_customaccount.user_id error Commented Apr 23, 2016 at 2:50
  • It means you are creating multiple CustomAccount object with same user. Commented Apr 23, 2016 at 9:00
  • How that could be possible I am creating new user before saving every time Commented Apr 23, 2016 at 11:00
  • Just tried the above code with changed save method myself. It works. Is it possible you are using the same user_id from other parts of your code ? UNIQUE constraint on user_id only means you are trying to create CustomAccount with the same same user. There is no problem with above code as it is creating new user every time. It may be from other parts of your code Commented Apr 24, 2016 at 3:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.