[Django]-Initializing foreignkey in modelform

4👍

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.

Leave a comment