开发者

django forms MultipleChoiceField reverts to original value on save

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['prog开发者_StackOverflow社区rammes'].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


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 }) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜