django forms MultipleChoiceField reverts to original value on save

末鹿安然 提交于 2020-01-14 19:03:10

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/2425668/django-forms-multiplechoicefield-reverts-to-original-value-on-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!