Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access inline data in django ModelAdmin

I need to process a file uploaded in a django admin form. I've added a file upload field to the form:

class ExampleInline(admin.TabularInline):
    model = OtherExample
    extra = 1
class ExampleForm(forms.ModelForm):
    filedata = forms.FileField()
    class Meta:
        model = ExampleModel
class ExampleModelAdmin(admin.ModelAdmin):
    form = ExampleForm
    inlines = [ExampleInline,]

This renders the form exactly like I want it to render. The data returned in Request is exactly what I expect.

The issue is that I want to access the contents of the inline.

class ExampleAdmin(admin.ModelAdmin):
...
def save_model(self, Request, obj, form, change):
   the_file = form.cleaned_data['filedata']
   # do amazing things to contents of file

At this point I want to reference the results of what the user selected in the inline. Whatever they picked for OtherExample.

How do I access that through the form? I would prefer not to go through the Request but am willing to do that. I'm also willing to examine save_related(self,request, form, formset, change)

like image 985
ctjctj2 Avatar asked Dec 20 '25 10:12

ctjctj2


1 Answers

save_related can do this, although it's called after the form is saved so you'll end up saving the object twice. You can access the object as form.instance or formset.instance.

def save_related(self, request, form, formsets, change):
    obj = form.instance
    # whatever your formset dependent logic is to change obj.filedata
    obj.save()
    super(ExampleAdmin, self).save_related(request, form, formsets, change)
like image 102
Peter DeGlopper Avatar answered Dec 24 '25 11:12

Peter DeGlopper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!