Skip to content Skip to sidebar Skip to footer

Python Django: How To Upload A File With A Filename Based On Instance Pk

I have what I considered to be a simple question. Within my model I have a models.ImageField which looks like that: class CMSDocument(BaseItem): thumb = models.ImageField(uplo

Solution 1:

The primary key is assigned by the database so you have to wait until your model row is saved on the db.

Firstly divide your data in two models, with the thumbnail on the child model:

from django.db import models

from .fields import CMSImageField


class CMSDocument(models.Model):
    title = models.CharField(max_length=50)


class CMSMediaDocument(CMSDocument):
    thumb = CMSImageField(upload_to='./media/', blank=True)

As you see I'm using a custom field for the thumbnail instead of the ImageField.

So then create a fields.py file where you should override the pre_save function of the FileField class inherited by ImageField:

from django.db import models


class CMSImageField(models.ImageField):
    def pre_save(self, model_instance, add):

        file = super(models.FileField, self).pre_save(model_instance, add)

        if file and not file._committed:
            # Commit the file to storage prior to saving the model
            file.save('%s.png' % model_instance.pk, file, save=False)
        return file

Because CMSMediaDocument is inheriting from the CMSDocument class, at the moment that pre_save is called, the progressive PK is already saved in the database so you can extract the pk from model_instance.

I tested the code and should work fine.

The admin file used in the test:

from django.contrib import admin

from .models import CMSMediaDocument

admin.site.register(CMSMediaDocument)

Post a Comment for "Python Django: How To Upload A File With A Filename Based On Instance Pk"