Emmet Brown
Emmet Brown

Reputation: 456

Edit related object using ModelFormSet

I was using a model formset to generate a table of forms for a list of objects.

Forms:

class UserTypeModelForm(ModelForm):
    account_type = ChoiceField(label='User type',
                               choices=ACCOUNT_OPTIONS, required=False)

    class Meta:
        model = get_user_model()
        fields = ('account_type',)


UserTypeModelFormSet = modelformset_factory(get_user_model(),
                                            form=UserTypeModelForm, 
                                            extra=0)

View:

formset = UserTypeModelFormSet(queryset=users, prefix='formset')

Now my client wants to be able to modify a related field: user.employee_profile.visible.

I tryed to add a field to the form, and then passing "initial" and "queryset" to the formset, but It looks like it just takes one.

How would you guys do this?

Thanks

Upvotes: 0

Views: 339

Answers (1)

yofee
yofee

Reputation: 1297

with model formsets, the initial values only apply to extra forms, those that aren’t bound to an existing object instance. Django docs

The queryset provides the selected/entered values for the bound fields, the initial for the extra fields (in your case 0).

But you can override the initial value in e.g. your views when you created a field called employee in this case:

for form in forms:
    # Don't override a selected value.
    if not form.fields['employee'].initial:
        form.fields['employee'].initial = my_init

Upvotes: 1

Related Questions