max
max

Reputation: 10454

django 1.8 how to retrieve image file path from the database when using upload_to

I have an image file in my django model. I'm trying to retrieve the path of the image while I've forced the output directory using upload_to but it is not returning the correct path.

def signatures_path(instance, filename):
    return 'signatures/{}/{}'\
        .format(instance.id, filename)


class Designation(models.Model):
    designation = models.TextField()
    user = models.OneToOneField(User)
    signature = models.ImageField(upload_to=signatures_path,\
        blank=True, null=True, default=None, validators=[validate_png])


Designation.objects.filter(user__username=username).values_list('signature', flat=True)
[u'sig'jpg']


x = Designation.objects.get(user__username=username)
print x.signature.path
/home/me/myapp/myapp/media/sig.jpg

but I expect it to be: /home/me/myapp/myapp/media/signature/None/sig.jpg

How to retrieve the correct path? Note that there is a "None" directory in the path which does not seem to be stored anywhere.


update: The problem was because of the way I was saving the file. I was saving it with:

Designation.objects.filter(user__username=username).update(signature=signature)

When I changed it to:

x=Designation.objects.get(user__username=username)
x.signature=signature
x.save()

then it worked fine.

Upvotes: 0

Views: 1018

Answers (1)

Adriano Silva
Adriano Silva

Reputation: 2576

You should use the print x.signature.url instead of print x.signature.path. It returns the absolute path of file.

Upvotes: 1

Related Questions