I'm using the django-storage package, and trying to upload multiple images at once. So I overwritten the add_view and save_model methods in ModelAdmin, in order to remove the original image field and use a custom one (with a multiple
flag in the input tag) given in the template HTML:
MODELS.PY
class Media(AbstractCreatedUpdatedDateMixin):
uuid = models.UUIDField(unique=True, default=uuid4, editable=False, db_index=True)
user = models.ForeignKey(User, related_name="uploaded_media", on_delete=models.CASCADE)
title = models.CharField(max_length=255)
image = models.ImageField(upload_to=uuid_directory_path)
ADMIN.PY
class MediaModelAdmin(admin.ModelAdmin):
def add_view(self, request, form_url='', extra_context=None):
self.exclude = ('image', "is_approved")
extra_context = extra_context or {}
extra_context['show_save_and_add_another'] = False
extra_context['show_save_and_continue'] = False
return super().add_view(request, form_url, extra_context)
def save_model(self, request, obj, form, change):
for file in request.FILES.values():
obj.user = User.objects.filter(id=request.POST.get("user")).first()
obj.title = request.POST.get("title")
obj.image.save(file.name, file.file)
obj.save()
It uploads correctly to S3, but it doesn't save the instance and throws this error:
TypeError at /admin/media/media/add/
expected string or bytes-like object
I'm not sure what is wrong here, maybe the fact that the upload is not done yet so the DB transaction is rolled back, but I can't figure out what do to.
Olga Riabukha :
Try to change this\n\nobj.image.save(file.name, file.file)\n\nto\nobj.image.save(file.name, file)\n",
2023-02-21T18:29:01