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 CMSImageFieldclassCMSDocument(models.Model):
title = models.CharField(max_length=50)
classCMSMediaDocument(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
classCMSImageField(models.ImageField):
defpre_save(self, model_instance, add):
file = super(models.FileField, self).pre_save(model_instance, add)
if file andnot 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.contribimport admin
from .modelsimportCMSMediaDocument
admin.site.register(CMSMediaDocument)
Post a Comment for "Python Django: How To Upload A File With A Filename Based On Instance Pk"