Mandeep Thakur Mandeep Thakur - 3 years ago 207
Python Question

NOT NULL constraint failed: app_business.user_id

I am rendering a form and when I am submitting that form getting this error

IntegrityError at /business/
NOT NULL constraint failed: app_business.user_id

class business(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=400)
rate_it = models.BooleanField(default=False)
availibility = models.BooleanField(default=True)

def __str__(self):

class businessform(forms.ModelForm):
class Meta:
model = business
fields = ['name', 'rate_it', 'availibility']

def formview(request):
if request.method == 'POST':
form = businessform(request.POST)
if form.is_valid():
return HttpResponse('saved')
form = businessform
return render(request, 'business.html', {'form':form})

html file

<form method="POST" action="">
{% csrf_token %}


<input type="submit" name="submit">

I don't know why this error is coming.

Answer Source

When you are saving the form you haven't passed any user object. Either pass user object while saving the form or make the user field null=True, blank=True in your model.

user = models.ForeignKey(User, null=True, blank=True)


Create an user object and save it first. Then pass that instance in the form to update values you got from template. Then save the form.

user = User.objects.create_user(username=username, password=password)
obj = business.objects.create(user=user, name="")
form = form = businessform(request.POST, instance=obj)

if form.is_valid():
    return HttpResponse('saved')

Be careful about the usernames. Usernames must be unique. So, you need to generate those.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download