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


models.py

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):
return self.name


forms.py

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


views.py

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


html file

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

{{form.as_p}}

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


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)

EDIT

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)
user.save()
obj = business.objects.create(user=user, name="")
form = form = businessform(request.POST, instance=obj)

if form.is_valid():
    form.save()
    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