Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
Calling Model function in template not working

I'm trying to get the category of a skill in a template. From the post I read, I can't directly get information from a foreign key in a template. Instead, I add a function on CharacterSkill models to get the Skill category

Models.py

class Character(models.Model):
    name = models.CharField(max_length=70)

class Skill(models.Model):
    name = models.CharField(max_length=70)
    cat1 = '01'
    SKILLSET_CHOICE = ((cat1:'cat1'))
    skillset_choice = models.CharField(
        max_length=2,
        choices = SKILLSET_CHOICE,
        default='',
        blank=True,
        null=True,
        )

class CharacterSkill(models.Model):
    character = models.ForeignKey(Character, on_delete=models.CASCADE)
    skill = models.ForeignKey(Skill, on_delete=models.CASCADE)
    def skillcategory(self):
        return Skill.objects.get(id = self.skill).skillset_choice    

Template

skillsetchoice {{item.skillcategory}}

But I get an error :

Exception Type: TypeError
Exception Value:    
int() argument must be a string or a number, not 'Skill'

I tried to inpect value with the shell console where I can get back the category id but when I use it in template, nothing is working

Hope you can help me!

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

This has nothing to do with calling it from the template.

self.skill is already an instance of Skill. There is no need to query that model explicitly.

def skillcategory(self):
    return self.skill.skillset_choice    

And in fact this method is pretty pointless; you certainly can do it directly in the template:

skillsetchoice {{ item.skill.skillset_choice }}
about 4 years ago · Santiago Trujillo Report

0

Replace self.skill with self.skill.id (in older versions of Django your code would work by the way):

def skillcategory(self):
    return Skill.objects.get(id = self.skill.id).skillset_choice

But this is much better:

def skillcategory(self):
    return self.skill.skillset_choice

But do you really need this method? You can use:

{{ item.skill.skillset_choice }}

If you want to display cat1, then (get_foo_display):

{{ item.skill.get_skillset_choice_display }}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!