views:

32

answers:

2

I have this working code

f = SomeForm(request.POST)

When I tried to modify it into

f = SomeForm(request.POST, initial={'spam', 4})

it didnt work, the 'initial' wasnt selected ('spam' is a ModelChoiceField), but when I tried

f = SomeForm(initial={'spam', 4})

it worked (selected value was correct). Am I missing something here? If it matters, heres what its init method looks like

def __init__(self, *a, **ka):
    super(SomeForm, self).__init__(*a, **ka)
    ....#more codes

Is there a way to make the initial data works without having to remove the first argument? Thank you

EDIT : it doesnt have to be "initial", as long as I can put some pre-determined value on ModelChoiceField. The condition = There is a request.POST, but the form hasnt been submitted (the post came from another page)

A: 

You don't need to pass initial if the form has been posted. Check request.method and instantiate the form accordingly.

Ignacio Vazquez-Abrams
thanks, but the POST came from another page via action post, so the form hasnt been posted yet. whats the best approach for this?
kusut
You could pass POST as initial: `SomeForm( initial = request.POST )` or just modify `request.POST` before passing if as data to the form `if not request.POST.get("spam"): request.POST["spam"] = 4`
cji
A: 

It turned out I only had to change the data attribute. Use copy method to make QueryDict mutable

post = request.POST.copy()

f = SomeForm(post)
f.data['spam'] = 4
kusut