Django表单(不是ModelForms):将模型中的复选框数据预填充到表单上

时间:2015-07-20 20:30:48

标签: django forms django-models django-forms

我正在尝试使用django表单而不是模型表单。在尝试填充数据以进行编辑时,我不断获得keyError(u'manager')。如果我删除字段“选项”的分配,则不会出现这种情况。选择是我模型中的多对多领域。为了减少混乱,我会粘贴我的模型,表格和视图。

#model.py

class UserProfileForm(forms.Form):
    CHOICES = (
        ('like to cook', 'like to cook'),
        ('like only to eat', 'like only to eat')
    )

    about_me = forms.CharField(widget=forms.Textarea, required=False)
    country = forms.CharField(max_length=60,required=False)
    choices =forms.MultipleChoiceField(choices=CHOICES,widget=forms.CheckboxSelectMultiple(),required=False)

#forms.py

@login_required
def update_profile(request):
    userprofile = UserProfile.objects.get(user=request.user)
    form = UserProfileForm(initial={'about_me':userprofile.about_me,
                                     'country':userprofile.country,
                                     'choices': userprofile.choices})
    return render(request, 'u_profiles/edit_pro.html', {'form':form})

#views.py

{{1}}

现在,当我分配所选选项的初始值时,我得到了keyerror。我想知道这样做的正确方法。

感谢。

0 个答案:

没有答案