编程语言
首页 > 编程语言> > python-django表单在保存时将MultipleChoiceField还原为原始值

python-django表单在保存时将MultipleChoiceField还原为原始值

作者:互联网

我写了一个自定义的MultipleChoiceField.我一切正常,但是当我提交表单时,即使表单验证正常,所选值也将返回到原始选择.

我的代码看起来像这样:

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

我没有包括所有其他字段等,但这基本上是我遇到麻烦的代码.任何人都有任何想法如何提交表单后显示新值,或者为什么它又回到原始值

谢谢

解决方法:

您总是回传表单的未绑定实例,请尝试以下操作:

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

标签:django-forms,python,django
来源: https://codeday.me/bug/20191210/2099992.html