Django ModelChoiceField initial data not working for ForeignKey

I fill my form with raw data using a standard file:

form = somethingForm(initial = {
                    'title' : something.title,                    
                    'category' : something.category_id,
                })

      

The title works fine, but if the category is a ModelChoiceField and a ForeignKey in the model, the original data won't work. Nothing will be selected in the selection box. If I change the category to IntegerField in the model, it works fine.

I still want to use a ForeignKey for the category, so how can I fix this?

+2


source to share


2 answers


Maybe try using a category instance rather than its ID?



+1


source


You need to do this

form = somethingForm(initial = {
                    'title' : something.title,                    
                    'category' : [("database value","display value")],
                })

      



Why is a list of tuples needed?

  • As select boxes are associated with the selected widget (e.g. html ===> ..............)

  • For each option we need to specify two things: 1.internal value 2.display value (every tuple in the list indicates this)

0


source







All Articles