1

I want my model object to always return the image.url of field image.

My model:

class Content(models.Model):
    ...
    avatar = models.ImageField(upload_to=file, blank=True, null=True)

I want something like:

class Content(models.Model):
    ...
    def get_avatar(self): # some default func for returning fields
        return self.avatar.url

It have to work like this, When I get the object:

content = Content.objects.get(pk=1)
print(content.avatar)

And it should print the path:

/media/uploads/dsadsadsa.jpg

Briefly, I want something that will change the return of model field.

Jared Forth
  • 1,577
  • 6
  • 17
  • 32
Osman Omar
  • 433
  • 1
  • 7
  • 19

2 Answers2

3

You could add a property to your model like this, notice I added an underscore to the field name:

class Content(models.Model):
    ...
    _avatar = models.ImageField(upload_to=file, blank=True, null=True)

    @property
    def avatar(self):
        return self._avatar.url

Now you can do:

print(content.avatar)
p14z
  • 1,760
  • 1
  • 11
  • 17
0

Use __str__() method

class Content(models.Model):
    ...
    avatar = models.ImageField(upload_to=file, blank=True, null=True)

    def __str__(self):
        try:
            return self.avatar.url
        except AttributeError: # "self.avatar" may be None
            return "no avatar"

UPDATE-1

I think, the @propert may suite you

class Content(models.Model):
    ...
    avatar = models.ImageField(upload_to=file, blank=True, null=True)

    @property
    def avatar_url(self):
        try:
            return self.avatar.url
        except AttributeError:  # "self.avatar" may be None
            return "no avatar"

Now, you could access the url as,
print(content.avatar_url)

JPG
  • 82,442
  • 19
  • 127
  • 206