如果用户的个人资料存在,我想覆盖使用现有数据创建的表单,以便用户可以编辑他们可能已经提交的数据。我的代码覆盖了Form的init方法,但是在呈现表单时,表单具有文本,但是不可编辑。我需要它可编辑。
表单代码如下:
class ProfileForm(forms.Form):
aboutme = forms.CharField( widget=forms.Textarea )
aboutmeprivate = forms.BooleanField(required=False)
interestsprivate = forms.BooleanField(required=False)
def __init__(self, *args, **kwargs):
super(ProfileForm, self)
self.aboutme = kwargs.pop('aboutme')
self.aboutmeprivate = kwargs.pop('aboutmeprivate')
self.interestsprivate = kwargs.pop('interestsprivate')
通话如下:
form = ProfileForm(aboutme=exisitingprofile.aboutme, aboutmeprivate=exisitingprofile.aboutmeprivate, interestsprivate=exisitingprofile.interestsprivate)
有人可以建议吗?
答案 0 :(得分:0)
您需要这样给定,超级应该在self.your_field之后,并且您还缺少__init
class ProfileForm(forms.Form):
aboutme = forms.CharField( widget=forms.Textarea )
aboutmeprivate = forms.BooleanField(required=False)
interestsprivate = forms.BooleanField(required=False)
def __init__(self, *args, **kwargs):
self.aboutme = kwargs.pop('aboutme')
self.aboutmeprivate = kwargs.pop('aboutmeprivate')
self.interestsprivate = kwargs.pop('interestsprivate')
super(ProfileForm, self).__init__(*args, **kwargs)
“不可编辑”是指该字段不可点击吗?
答案 1 :(得分:0)
解决方案是从以下视图修改对表单的调用:
form = ProfileForm(initial={'aboutme': exisitingprofile.aboutme,
'aboutmeprivate' : exisitingprofile.aboutmeprivate,
'interestsprivate' : exisitingprofile.interestsprivate })
我不需要重写构造函数。