Zorgan
Zorgan

Reputation: 9143

Is it possible to add a custom attribute to a model field?

Here's my model:

def Post(models.Model):
    ...
    video = models.BooleanField(default=False, youtube=False)

is it possible to add the youtube attribute so I can use it in my template like so:

{% if video.youtube %}
    <p>text</p>
{% endif %}

Upvotes: 0

Views: 657

Answers (1)

markwalker_
markwalker_

Reputation: 12859

If you would like to know if a video is hosted on YouTube then you'd be better off with a property;

class Post(models.Model):
    ...
    video = models.URLField(verbose_name="URL of video")

    @property
    def video_is_youtube(self):
        """ Returns a boolean if the video is hosted on youtube """
        if self.video and "youtube.com" in self.video:
            return True
        return False

Then in your templates you can do {% if post.video_is_youtube %} to check if a video is hosted on youtube.

Upvotes: 1

Related Questions