J
J
justdani2018-06-22 16:50:33
Django
justdani, 2018-06-22 16:50:33

Changing upload_to of an ImageField?

Friends, the crux of the matter. there is a model:

class ItemChat(models.Model):

    class Meta:
        verbose_name = "ItemChat"
        verbose_name_plural = "ItemChats"

    def __str__(self):
        pass

    item = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
    personal = models.ForeignKey(PersonalProfile, on_delete=models.SET_NULL, blank=True, null=True)
    client = models.ForeignKey(ClientProfile, on_delete=models.SET_NULL, blank=True, null=True)
    comment = models.CharField(blank=True, null=True, max_length=50)
    design_img = models.ImageField(blank=True, null=True, upload_to='')

how can I specify upload_to depending on the instance of this class, namely, I need to take the item.client field (the output is naturally string) and put it in upload_to

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-06-22
@justdani

from os.path import splitext

class ItemChat(models.Model):
    ...

    design_img = models.ImageField(blank=True, null=True,
        upload_to=lambda obj, name: str(obj.item.client) + splitext(name)[1])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question