warpedspeed
warpedspeed

Reputation: 1098

Basic Python, Django, DRY - calling a method from a (model) class

I'm new to Python and Django. I have a basic python/django ORM question that's bothering me. I have two models and they have a show_image function that's repeated. That's no good.

class Dinner(models.Model):

    title = models.CharField(max_length=200)
    is_approved = models.BooleanField()
    hero = models.ImageField(upload_to="heros", blank=True)

    def show_image(self):
        image_url = None
        if self.hero is not None:
            image_url = """<img src="{0}{1}" />""".format(BASE_URL, self.hero)
        return image_url

    show_image.short_description = "Thumbnail"
    show_image.allow_tags = True

class Speaker(models.Model):

    title = models.CharField(max_length=200)
    biography = models.TextField(blank=True)
    headshot = models.ImageField(upload_to="headshots", blank=True)

    def show_image(self):
        image_url = None
        if self.headshot is not None:
            image_url = """<img src="{0}{1}" />""".format(BASE_URL, self.headshot)
        return image_url

    show_image.short_description = "Thumbnail"
    show_image.allow_tags = True

Seems simple enough- I decided to start experimenting. I created a method in models.py...

def test(obj):
  print obj

then in my models I tried:

test(self.hero)

and got this (instead of the value):

 django.db.models.fields.files.ImageField

How do I get the value out of this so I can check if the ImageField has been populated?

edit:

class Speaker(models.Model):

    title = models.CharField(max_length=200)
    biography = models.TextField(blank=True)
    headshot = models.ImageField(upload_to=upload_to, blank=True)

    test(headshot)

    def show_image(self):
        image_url = None
        if self.headshot is not None:
            image_url = """<img src="{0}{1}" />""".format(BASE_URL, self.headshot)
        return image_url

    show_image.short_description = "Thumbnail"
    show_image.allow_tags = True

Upvotes: 1

Views: 164

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

You're calling that test method at class level, which makes no sense. That means it's executed at the time that the model class is defined, which is why you see the field class. There's a whole lot of metaclass stuff that happens when models are defined, so that when you get an instance you see the value, not the field class - but that hasn't happened at the point you're calling the method.

In any case, you need to call that with an instance of the model, so that there is actually a value to deal with.

I suspect you're fairly new to Python, so here's a tip: you can inspect all this stuff from the Python shell. Start ./manage.py shell, then import your models, instantiate one (or get it from the db), then you can examine it with dir() and so on. Much more efficient than writing debug functions in your code.

Upvotes: 3

Related Questions