tags:

views:

309

answers:

2

I am filling my form with initial data using the normail:

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 initial data won't work. Nothing will be selected in the Select Box. If I change category to an IntegerField in the model it works fine.

I still want to use a ForeignKey for category though, so how do I fix this?

A: 

You need to do this

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

Why list of tuples?

  1. Because choice fields are associated with select widget ( i.e html ===> ..............)

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

Rama Vadakattu
I tried this and didn't work: 'category' : [(something.category_id,something.category_id.title)],
Joe
Also, this doesn't explain why if I change the model to an IntegerField without using the code you posted above it works fine. Any ideas on why that is happening?
Joe
+1  A: 

Perhaps try using an instance of a category rather than its ID?

Michael Williamson