Pass initial value to a modelform in django

前端 未结 3 2181
渐次进展
渐次进展 2021-02-13 20:22

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:
             


        
相关标签:
3条回答
  • 2021-02-13 20:32

    In case anyone is still wondering, the following works to set initial values for an Admin 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
    

    Note that you can also set initial values via URL parameters: e.g. /admin/person/add?log_user=me

    0 讨论(0)
  • 2021-02-13 20:33

    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'})
    

    Update

    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())
    
    0 讨论(0)
  • 2021-02-13 20:49

    As your ModelForm is bound to the Person-Model, you could either pass a Person-Instance:

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

    or overwrite the ModelForm's init-method:

    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 untested. I'm not sure whether "value" is correct, I'm not having a Django-Installation here, but basically this is the way it works.

    0 讨论(0)
提交回复
热议问题