user3481672
user3481672

Reputation: 45

Django: How add field to form from model?

I have a form:

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

How to add to this form another field? For example, a text field that has no relationship to the model.

Upvotes: 1

Views: 110

Answers (1)

frnhr
frnhr

Reputation: 12903

Simply add it :) Like so:

class ProfileForm(forms.ModelForm):
    the_text_field = forms.CharField(required=False, label....)

It is automatically going to be added to form.cleaned_data so you can use it on form.save() or in the view.

Upvotes: 2

Related Questions