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!
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 }}
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 }}