Multiple file uploading in django admin

1,361 views
Skip to first unread message

Muhammad Dilshad Khaliq

unread,
Dec 18, 2018, 4:31:58 PM12/18/18
to Django users

I have File model for uploading file.

class File(models.Model):
    files = models.FileField(upload_to='sampleorder/%y/%m/%d', null=True, blank=True)
    order_detail = models.ForeignKey(OrderDetail, on_delete=models.SET_NULL, null=True)

and for multiple file upload i have form.py

class FileForm(forms.ModelForm):
    class Meta:
        model = File
        fields = ['files']
        widgets = {
            'files': forms.ClearableFileInput(attrs={'multiple': True}),
        }

and in admin.py

@admin.register(File)
class FileAdmin(admin.ModelAdmin):
    form = FileForm
    list_display = ['id']

    def save_model(self, request, obj, form, change):
        files = request.FILES.getlist('file')
        for f in files:
            instance=File(files=f)
             instance.save()
return super(FileAdmin, self).save_model(request, obj, form, change)

but its only save latest file. how to save multiple file at time? i also see this Upload multiple files using Files Field in Django Admin question but can configure where i am wrong.


Ryan Nowakowski

unread,
Dec 19, 2018, 7:02:13 PM12/19/18
to django...@googlegroups.com
The answer[1] to that stack overflow question looks correct to me. To summarize, the "files" field on your model only stores a single file. Instead of files field, you'll need to create a new model that's foreign keyed back to your File model to store an arbitrary number of multiple files.

[1] https://stackoverflow.com/a/49734180
Reply all
Reply to author
Forward
0 new messages