NewToJS
NewToJS

Reputation: 2101

Django: Calling a model's function in my template - not working

I'm trying to call a function from my model (check_nick) in my template. It appears that the template is successfully hitting the function since the items in the function are printed. However I'm not getting the expected result (True) as the user.group I'm testing with is NICK which is part of the NICK_BRANDS list.

MODEL.PY:

NICK_BRANDS = ['NICK', 'NICKT', 'NICKN', 'NICKK', 'NICKA']


class User():

    group = models.ForeignKey(Brand, null=True, blank=True)

    def check_nick(self):
        brand = self.group
        print brand  //prints NICK
        print brand in NICK_BRANDS  //prints False (should be True!)
        if brand in NICK_BRANDS:
            return True
        else:
            return False

TEMPLATE:

 {% if user.check_nick %}
    //add some markup
 {% endif %}

Upvotes: 0

Views: 115

Answers (2)

user2390182
user2390182

Reputation: 73498

Your debug prints some string representation of brand, but you are checking the actual object. Change your if-clause to sth like:

 if str(brand) in NICK_BRANDS:
 # if brand.title in NICK_BRANDS:
 # if brand.name in NICK_BRANDS:
 # or whatever field of Brand is "NICK"

Upvotes: 2

A. J. Parr
A. J. Parr

Reputation: 8026

self.group will be an instance of the related Brand model, not a string, and hence would probably not return True with the in statement. I presume there is some Brand.name property and you should be using:

def check_nick(self):
    return self.group.name in NICK_BRANDS

Upvotes: 1

Related Questions