itsquestiontime1
itsquestiontime1

Reputation: 45

Django model field, alternative value return if null?

Is there a way to return a different set value for a django model field if that field has a null value?

I have users with profile images (image_url), for users who do not have one I'd like to return a default no avatar url, rather than 'None'.

class User(models.Model):
    name = models.CharField(max_length=800)
    image_url = models.URLField(max_length=2000, blank=True, null=True)

Upvotes: 2

Views: 2126

Answers (5)

Avi Nerenberg
Avi Nerenberg

Reputation: 380

You could override the __getattribute__ method, per this answer. This has the advantage of not introducing an additional property (that you'll need to remember, or update any relevant references for):

class User(models.Model):
    ....
    def __getattribute__(self, name):
        attr = models.Model.__getattribute__(self, name)
        if name == 'avatar' and not attr:
            return 'path/to/default/img'
        return attr

Upvotes: 0

RemcoGerlich
RemcoGerlich

Reputation: 31260

The easiest way is to just add an extra property to the model:

@property
def image_url_with_default(self):
    return self.image_url or whatever_the_default_url_is

Upvotes: 4

tutuDajuju
tutuDajuju

Reputation: 10860

as @paulo-scardine suggested, just add a condition when you want to actually use it - i.e in a template, or if it's bound to be used in multiple places, as a method/property of the model (as @remcogerlich) suggested.

@property
def avatar(self):
    return self.image_url or settings.DEFAULT_AVATAR_URL

Upvotes: 2

pleasedontbelong
pleasedontbelong

Reputation: 20102

Have you tried using the default option on the URLField?

you could do someting like:

image_url = models.URLField(max_length=2000, blank=True, null=True,  default='http://misyte.com/default-image.jpg')

Haven't tested it... there's also an ImageField on django.. maybe you could check that too

Hope this helps

Upvotes: 0

Paulo Scardine
Paulo Scardine

Reputation: 77271

Oh, my... URL entered by the user... Looks dangerous.

class User(models.Model):
    name = models.CharField(max_length=800)
    image = models.ImageField(upload_to='avatars', blank=True, null=True)

    def avatar(self):
        if self.image: return self.image.url
        return '/path/to/default/avatar.png'

If you store the image at your side you can at least run something like "nude" in order to analyze an image for nudity.

Upvotes: -1

Related Questions