[Answer]-Python Django Form: Setting initial values for CharFields

1👍

For each field in the __init__ method you need to this:

class EditPersonForm(forms.Form):

    def __init__(self, person, *args, **kwargs):
        super(EditPersonForm, self).__init__(*args, **kwargs)
        profile = person

        [...] #ommited code for simplification

        self.fields['username']= forms.CharField(
           label =('User Name'), max_length = constants.MAX_LEN_NAME, 
           initial = profile_default.username)

        [...] # do the same for rest of the fields

Also since you are defining a model in class Meta, are you suppose to be using a ModelForm

class EditPersonForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(EditPersonForm, self).__init__(*args, **kwargs) 
        [...]


    class Meta:
        model = Person
        exclude = ('user',)

Hope this helps 🙂

0👍

There’s no point doing this. Fields should be defined at the class level, not inside the __init__ method: the only reason to do that would be on those occasions when you want to override some aspects of some fields programmatically. Move all those definitions outside the method, and remove their initial attributes.

Instead, pass the initial dict as a keyword parameter when you instantiate the form in your view:

form = EditPersonForm(initial=profile_default)

Leave a comment