Purpose and Problem:
I want to put two forms in the same template and process them in the one view. I can get the template to display the two forms but not submit them (i.e process the submission). When I submit I get the following error:
Exception Value: NOT NULL constraint failed: stockinfo_note.stock_id
'stock' is the ForeignKey. I can't figure out how to get the function stock_new in Views.py to populate the foreign key ID which is what i think i need to do to overcome the above error.
Models.py:
class Stock(models.Model):
'''
Model representing the stock info.
'''
user = models.ForeignKey(User)
ticker_code = models.CharField(max_length=10, null=True, blank=True)
def __str__(self):
return self.ticker_code
class Note(models.Model):
'''
Model representing the note.
'''
user = models.ForeignKey(User)
text_note = models.TextField()
stock = models.ForeignKey(Stock)
def __str__(self):
return self.text_note
Forms.py
class StockForm(forms.ModelForm):
class Meta:
model = Stock
fields = ('ticker_code',)
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ('text_note',)
Views.py
def stocknoter(request):
stock = Stock.objects.filter(user=request.user)
note = Note.objects.filter(user=request.user)
context_dict = {'stock':stock, 'note':note}
return render(request, "stocknoter/stock.html", context_dict)
def stock_new(request):
if request.method == "POST":
form1 = StockForm(request.POST)
form2 = NoteForm(request.POST)
if form1.is_valid() and form2.is_valid():
stock = form1.save(commit=False)
stock.user = request.user
stock.save()
note = form2.save(commit=False)
note.user = request.user
'''
**THE PROBLEM IS AROUND HERE i think, how do i pass stock_id created
by form1 so form2 saves it as the foreignkey?**
'''
note.save()
return redirect('stock')
else:
form1 = StockForm()
form2 = NoteForm()
return render(request, 'stocknoter/stock_edit.html', {'form1':form1, 'form2':form2})
As mentioned above, i think the problem lies with this latter section (sorry should add i am new to Django). What do i need to do to save the foreign key id?