Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override FileField widget in InlineFormset_factory?

Tags:

django

formset

I would like to change the default upload field (FileField) in an inlineformset_factory form, to use the AdminFileWidget from django.contrib.admin.widgets. The purpose of this is to show the path of the currently uploaded file as it does in the admin forms (perhaps there is another way to do this anyway?).

I have no trouble getting the widget to work using a custom form, just cant figure out how to change the widget in an inlineformset_factory.

like image 533
HdN8 Avatar asked Dec 28 '22 07:12

HdN8


1 Answers

This will get you the Admin FileField widget instead of the standard one with 5 extra fields.

views.py

MySpecialFormset = inlineformset_factory(  MyParentModel, 
                                           MyChildModel, 
                                           form=MyChildModelForm, 
                                           extra=5)

formset = MySpecialFormset(instance=myparentmodelinstance) #add request.POST and request.FILES if used on the POST cycle

forms.py

from django.contrib.admin.widgets import AdminFileWidget

class MyChildModelForm(forms.ModelForm):

    class Meta:
        model = MyChildModel

    def __init__(self, *args, **kwargs):
        super(MyChildModelForm, self).__init__(*args, **kwargs)

        self.fields['my_file_field'].widget = AdminFileWidget() 
like image 130
Steve Jalim Avatar answered Jan 13 '23 10:01

Steve Jalim