1

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.

1
  • You should probably remove the default value for your user=User() argument — you're trying to filter your Profile objects over it, which will fail with the default unsaved User instance, so that argument isn't really optional. Commented Apr 4, 2014 at 21:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.