Pass the initial value of the model model in django

How to transfer the 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 the initial value for the field of the Person class. How can i do this?

+6
source share
3 answers

You can pass the initial value to ModelForm as follows:

 form = PersonForm(initial={'fieldname': value}) 

For example, if you want to set the initial age to 24 and name to "John Doe" :

 form = PersonForm(initial={'age': 24, 'name': 'John Doe'}) 

Update

I think this concerns your current 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()) 
+7
source

Since your ModelForm is associated with a Person-Model, you can either pass a Person-Instance:

 form = PersonForm(instance=Person.objects.get(foo=bar) 

or overwrite the init method of ModelForm:

 class PersonForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PersonForm, self).__init__(*args, **kwargs) self.fields['foo'].value = 'bar' class Meta: model = Person exclude = ['name'] 

This is not verified. I'm not sure if the β€œvalue” is right, I don't have Django-Installation here, but basically this is how it works.

+6
source

In case someone is still interested, the following settings for setting initial values ​​for the administrator form:

 class PersonAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(PersonAdmin, self).get_form(request, obj=obj, **kwargs) form.base_fields['log_user'].initial = get_current_user() return form 

Please note that you can also set initial values ​​via URL parameters: for example. / Admin / person / add? Log_user = i

+6
source

Source: https://habr.com/ru/post/897812/


All Articles