Reputation: 145
I have a model for my user and another model for music style. In my model of musical styles, I need to put the image under a name other than the original name.
The new name I would like is the 'email of the user who is saving' + '_' + 'milliseconds'.
Staying in this format: '[email protected]_1621196336'
class CustomUser(AbstractUser):
username = None
id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False)
email = models.EmailField('E-mail', unique=True, null=False)
class MusicStyle(models.Model):
id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False)
name = models.CharField(max_length=150, null=False, blank=False)
image_link = models.FileField(upload_to='musics/thumbnail_images/##CUSTOM_NAME##')
Musical style is in a different model from the user model.
How to do this?
Upvotes: 0
Views: 1328
Reputation: 2380
If you want to set custom filename for your files you can do this:
def image_upload_to(instance, filename):
# You can access to your model fields with instance for example: instance.name
return f"musics/thumbnail_images/{filename}"
class MusicStyle(models.Model):
id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False)
name = models.CharField(max_length=150, null=False, blank=False)
image_link = models.FileField(upload_to=image_upload_to)
Upvotes: 1
Reputation: 2165
i didnt understand what the field with milliseconde is or what is supposed to do so i replaced it with with email and music_style name, here is how you can name your images, you can adjust it as you want
def upload_location(instance, filename):
filebase, extension = filename.split('.')
return 'musics/thumbnail_images/%s_%s.%s' % (instance.user.email,instance.name, extension)
class MusicStyle(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
name = models.CharField(max_length=150, null=False, blank=False)
image_link = models.FileField(upload_to=upload_location)
Upvotes: 2