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:
model = Screening
def __init__(self, *args, **kwargs):
super(ScreeningForm, self).__init__(*args, **kwargs)
self.fields['blood_screen_type'] = CommaSeparatedCharField(
label=self.fields['blood_screen_type'].label,
initial=self.fields['blood_screen_type'].initial,
required=False,
widget=CommaSeparatedSelectMultiple(choices=BLOOD_SCREEN_TYPE_CHOICES)
)
class ScreeningAdmin(admin.ModelAdmin):
#form = ScreeningForm
form = ScreeningForm(initial={'log_user':get_current_user()})
Now I want to pass an initial value for a field of the Person class. How can I do that?
initial is used to change the value of the field in the input tag when rendering this Field in an unbound Form. initial accepts as input a string which is new value of field. The default initial for a Field is empty.
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
It also means that when Django receives the form back from the browser, it will validate the length of the data. A Form instance has an is_valid() method, which runs validation routines for all its fields. When this method is called, if all fields contain valid data, it will: return True.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With