Django: How to set initial values for a field in an inline model formset?

偶尔善良 提交于 2019-11-29 07:09:01

I'm not sure how to handle this in inline formsets, but the following approach will work for normal Forms and ModelForms:

You can't set this as part of the model definition, but you can set it during the form initialization:

def __init__(self, logged_in_user, *args, **kwargs):
    super(self.__class__, self).__init__(*args, **kwargs)
    self.fields['my_user_field'].initial = logged_in_user

...

form = MyForm(request.user)

This does the trick. It works by setting the initial values of all "extra" forms.

formset = MyFormset(instance=myinstance)
user = request.user
for form in formset.forms:
    if 'user' not in form.initial:
        form.initial['user'] = user.pk

I'm using Rune Kaagaard's idea above, except I noticed that formsets provide an extra_forms property: django.forms.formsets code

@property
def extra_forms(self):
    """Return a list of all the extra forms in this formset."""
    return self.forms[self.initial_form_count():]

So, sticking with the example above:

formset = MyFormset(instance=myinstance)
user = request.user
for form in formset.extra_forms:
    form.initial['user'] = user.pk

Saves having to test any initial forms, just provide default for extra forms.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!