benage andy
benage andy

Reputation: 33

how to fix no null constraint in django

I am creating a user using OneToOne relationship , when I enter the data in the form and submit it, I'm getting no null constraint error

view.py

def registerUser(request):
    if request.method=='POST':
        form=UserCreationForm(request.POST)
        form_class=ProfileForm(request.POST)
        if form.is_valid() and form_class.is_valid():
            form.save()
            form_class.save()
            return redirect('/home/')
    else:
            form=UserCreationForm()
            form_class = ProfileForm()

    return render(request,'register.html',{'form':form,'form_class':form_class})

form.py

class Registerform(UserCreationForm):
    class Meta:
        model=User
        fields= ['username','first_name','last_name','password1','password2']

    def save(self, commit=True):
        user=super(Registerform, self).save(commit=False)
        user.first_name=self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

        if commit:
            user.save()
        return user


class ProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = [ 'location']

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    description = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    salary=models.CharField(max_length=120)

    def __str__(self):
        return self.location

Upvotes: 0

Views: 438

Answers (1)

dirkgroten
dirkgroten

Reputation: 20672

Your UserProfile model requires a salary but your form only has a location field. So when your form is submitted with a location, it's valid, but the underlying model cannot be saved because salary will be None.

Add the salary field to your form, or make salary a nullable field.

Also, you need to assign the user field before saving the profile, since that also is not nullable. One way to do that is:

user = form.save()  # this is the UserForm so when saving it returns the user
profile = form_class.save(commit=False)
profile.user = user
profile.save()

I would recommend you carefully read the Django documentation on model forms. The section on the save method in particular would explain you how to properly handle these cases.

Upvotes: 1

Related Questions