I'm trying to initialize ForeignKey in a ModelForm. That should be Django 101, but I'm obviously failing at googling and reading docs. This is what I tried:
# models.py
class Sale(models.Model):
pass
class Settlement(models.Model):
sale = models.ForeignKey(Sale)
# forms.py
class SettlementForm(ModelForm):
class Meta:
model = Settlement
# views.py
def add_settlement(request, sale_id):
sale = get_object_or_404(Sale, id=sale_id)
form = SettlementForm(initial={'Sale': sale})
form.fields['sale'].initial = str(sale)
return render(request, 'settlement.html', {'settlementform': form, 'sale': sale})
Yes, that's 2 different (and wrong) ways I tried to initialize ForeignKey, but failed. So, how do you do this the right way?
(yes, I searched StackOverflow, but as I said, I obviously fail at googling :-( )
The thing to remember is that the value of a foreign key field is its ID. Both of those methods can work, but you have (different) issues with each.
For the first method, you should use the correct field name:
form = SettlementForm(initial={'sale': sale.id})
And for the second, you must pass the ID, not the string representation:
form.fields['sale'].initial = sale.id
The first method is preferable though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With