[Answered ]-Changing data in a django modelform

2๐Ÿ‘

I would suggest writing a helper factory function for your form set so that you can customize the display widget according to the data. Something like the following:

def make_entry_formset(initial_obj=None, custom_widget=forms.Textarea):
    # these will be passed as keyword arguments to the ModelChoiceField
    field_kwargs={'widget': custom_widget,
                  'queryset': Entity.objects.all()}
    if initial_obj is not None:
        field_kwargs.update({'initial': initial_obj})
    class _EntryForm(forms.ModelForm):
        entity = forms.ModelChoiceField(**field_kwargs)

        class Meta:
            model = Entry
    return modelformset_factory(Entry, form=_EntryForm)

Then in your view code you can specify the widget you want and whether to bind to an initial Entity object. For the initial rendering of the formset, where you just want a Textarea widget and no initial choice, you can use this:

formset_class = make_entry_formset(custom_widget=forms.Textarea)
entry_formset = formset_class()

Then if you want to render it again (after the is_valid() block) with the Entity object already defined, you can use this:

formset_class = make_entry_formset(initial_obj=entity, 
                                   custom_widget=forms.HiddenInput)
entry_formset = formset_class(request.POST, request.FILES)

You can use any widget you like, of course, but using a HiddenInput would prevent the end user from interacting with this field (which you seem to want to bind to the entity variable you looked up).

Leave a comment