How can I pass an initial value for a field to a model form. I have something like the following code
class ScreeningForm(forms.ModelForm):
class Meta:
You can pass initial value to a ModelForm like this:
form = PersonForm(initial={'fieldname': value})
For example, if you wanted to set initial age
to 24
and name
to "John Doe"
:
form = PersonForm(initial={'age': 24, 'name': 'John Doe'})
I think this addresses your actual question:
def my_form_factory(user_object):
class PersonForm(forms.ModelForm):
# however you define your form field, you can pass the initial here
log_user = models.ChoiceField(choices=SOME_CHOICES, initial=user_object)
...
return PersonForm
class PersonAdmin(admin.ModelAdmin):
form = my_form_factory(get_current_user())