Mint
Mint

Reputation: 1059

Django - id null - foreign key error

Error:

app_a.desc_id may not be NULL

I believe my problem is I'm not passing the id from formB to formA when I save. please please lead me to a solution for this problem.

Here's my view:

def form(request):
    if request.method == 'GET':
        formB = BForm()
        formA = AForm()
        return render(request,r'app/form.html',{'formA':formA,'formB':formB})
    elif request.method == 'POST':
        formA = AForm(request.POST)
        formB = BForm(request.POST)
        formB.save()
        formA.save()
        return HttpResponseRedirect('/log')

Here are my models:

# Descprition
class B(models.Model):
    id = models.AutoField(primary_key=True)
    description = models.CharField(max_length=50)

# Title
class A(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField('Name',max_length=20)
    desc = models.ForeignKey(B)

and here is my form:

class BForm(forms.ModelForm):
    class Meta:
        model = B
        fields = ['description']

class AForm(forms.ModelForm):
    class Meta:
        model = A
        fields = ['name']

Upvotes: 0

Views: 373

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

Your program has multiple errors but the main problem for this is because desc is a foreign key in class A that points to class B, and you don't have null=True on it, meaning you never want that field to be empty. In other words, each instance of A should have a foreign key desc.

If you just save() both forms, formA tries to save an instance of A, without having a value for desc field, hence the error. You should assign the instance that formB creates to the instance that formA creates:

new_b = formB.save()
new_a = formA.save(commit=False)
new_a.desc = new_b
new_a.save()

Other problems in your program including never called form.is_valid(), having redundant id fields(django would create one for you). I suggest you read django tutorial first before jumping into coding. It would save a lot of time like figuring out errors like this.

Upvotes: 2

Related Questions