3

I have wrote a custom MultipleChoiceField. I have everything working ok but when I submit the form the selected values go back to the original choices even though the form validates ok.

my code looks something like this:

class ProgrammeField(forms.MultipleChoiceField):
    widget = widgets.SelectMultiple

class ProgrammeForm(forms.Form):
    programmes = ProgrammeField(required=False)

    def __init__(self, user, *args, **kwargs):
        self.fields['programmes'].choices = Mymodel.objects.all()
        self.fields['programmes'].initial = Mymodel.objects.filter(created=user)

view.py
if request.method == 'POST':
    form = ProgrammeForm(user=request.user, data=request.POST)
    if form.is_valid():
        form.save()
form = ProgrammeForm(request.user)

return render_to_response(form.html', {'form': form }) 

I haven't included all the other fields etc. but this is basically the code I am having trouble with. Anyone have any ideas how to get it to display the new values after the form has been submitted or why it is going back to the original values

Thanks

John
  • 21,047
  • 43
  • 114
  • 155

1 Answers1

3

You're always passing back an unbound instance of the form, try this:

view.py

if request.method == 'POST':
    form = ProgrammeForm(user=request.user, data=request.POST)
    if form.is_valid():
        form.save()
else: ##this is the changge
    form = ProgrammeForm(request.user)
return render_to_response('form.html', {'form': form }) 
Zach
  • 18,594
  • 18
  • 59
  • 68
  • This worked but why wouldn't the line: self.fields['programmes'].initial = Mymodel.objects.filter(created=user) set the values to the correct ones? – John Mar 11 '10 at 15:19
  • Read up on forms. `choices` should be a list of tuples, and `initial` should be a list of values. You're passing `QuerySets` in for both. I'm guessing this is part of your problem. – Zach Mar 11 '10 at 17:02