0

I have a case where users upload files and each file has certain attributes. Often times there could be 10 files that will need to be uploaded into the database with the same attributes. To save time, it would be nice to allow the user to select all ten files and have 10 records added in the database, one record per file. My models are similar to the example below:

class ContentCategory(models.Model):
    name = models.CharField(max_length=100)


class Document(models.Model):
    file_name = models.CharField(max_length=100, blank=True)
    note = models.TextField(null=True, Blank=True)
    content_category = models.ForeignKey(ContentCategory, on_delete=models.PROTECT)
    document = models.FileUpload(upload_to=f'{content_category}/')

    def save(self):
        self.file_name = os.path.basename(self.document.name)
        super(Document, self).save()

My admin.py is simple, like the below code:

class DocumentAdmin(admin.ModelAdmin):
    exclude = ('file_name',)

admin.site.register(Document, DocumentAdmin)
admin.site.register(ContentCategory)

So here is an exact scenario that happens often. 10 photos will need to be uploaded and all of them get the same content category and note. Is there a way to setup the admin to allow someone to select the proper content category and write out the note and then select all 10 files to upload and have 10 records created in the document table upon save? One for each photo?

Battosai
  • 1
  • 3
  • Not easy to do in admin, however if you create your own view/page for this, you can use a `FileField` with multiple set to true and then when processing the form, loop through the uploaded files and save them. You could do that with a custom page/form in admin but it's a bit tricky. – dirkgroten Feb 24 '20 at 16:23

1 Answers1

0

You can override your admin form, and then do all your custom logic there.

Django custom model form

You could create a form with 10 fields for the files and 1 content category, and then handle it all via the form.

Or, you could also create a formset as well.

I would create a form with the content category as 1 field, and a nested formset in it for all the file fields. The user can add as a many files as they need, and when they upload, take the content category they selected and apply it to each file in the formset by overridding the formset clean method.

Eric Turner
  • 123
  • 5