[Django]-Django: Access and Update fields of a Form Class inside __init__ or save functions

4👍

Use something like this:

class RandomValueForm(ModelForm):
    myfield = models.IntegerField(default=0)

    def __init__(self, *args, **kwargs):
        super(RandomValueForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].initial = my_random_generator()

2👍

You got this error because you would have tried accessing fields on self without calling the __init__ of superclass. So, first you need to call superclass __init__ i.e __init__ of ModelForm and then you can access fields.

class MyModelForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].initial = my_random_number()

Leave a comment