我有一张表格:
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('ava', 'age', 'about', 'city', 'tel', 'portfolio', 'site', 'soc_net', 'is_photographer')
name = forms.CharField(widget=TextInput(attrs={'style': 'width:40%', 'class': 'form-control'}))
widgets = {
'age': DateInput(attrs={'class': 'form-control', 'data-date-format': 'dd.mm.yyyy'}),
'about': Textarea(attrs={'class': 'form-control'}),
'city': TextInput(attrs={'class': 'form-control'}),
'portfolio': URLInput(attrs={'class': 'form-control'}),
'site': URLInput(attrs={'class': 'form-control'}),
'soc_net': URLInput(attrs={'class': 'form-control'}),
'tel': TextInput(attrs={'class': 'form-control', '': ''}),
}
def __init__(self, user=User(), *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
profile = Profile.objects.get(user=user)
self.fields['age'].initial = profile.age
self.fields['about'].initial = profile.about
self.fields['tel'].initial = profile.tel
self.fields['city'].initial = profile.city
self.fields['portfolio'].initial = profile.portfolio
self.fields['site'].initial = profile.site
self.fields['soc_net'].initial = profile.soc_net
self.fields['ava'].initial = profile.ava
self.fields['is_photographer'].initial = profile.is_photographer
如何将此表单添加到另一个字段?例如,与模型无关的文本字段。
答案 0 :(得分:2)
只需添加它:)就像这样:
class ProfileForm(forms.ModelForm):
the_text_field = forms.CharField(required=False, label....)
它会自动添加到form.cleaned_data
,因此您可以在form.save()
或视图中使用它。