Render foreign key __str__ method in a template django
Render foreign key __str__ method in a template django
class A(models.Model):
field1 = models.CharField(max_length=10)
field2 = models.IntegerField(default=0)
def __str__(self):
return self.field1 + str(self.field2)
class B(models.Model):
a = models.ForeignKey(A)
...
Now in a template I want to render the "a" attribute of an instance of model B by using: binstance.a
but this seems to either render empty string or nothing at all.
binstance.a
How do I render the str methdod of a foreign key within the template?
I want to be able to print string representation of foreign key attribute in an easy manner. I don't want to put binstance.a.field1 binstance.a.field2 in the template, I'd rather have a compact representation of model A instance accessible by rendering the instance of A using ainstance in the template
– user3142434
Sep 8 '18 at 10:12
I am not sure, but I don't think django provide this way in template. Although you can think of reverse foreign key n template
– Atul Kumar
Sep 8 '18 at 10:19
2 Answers
2
Actually it's default django behaviour. Check do you pass B
instance with template context and use correct variable name in your template.
B
Yes! I was passing B.objects.all().values() to the template instead of B.objects.all(). Thanks!
– user3142434
Sep 8 '18 at 10:43
Maybe would I choose a different approach and create a template tag
@register.filter(name='fullname')
def fullname(pk):
b = B.objects.get(pk=pk)
field1 = b.a.first_name
field2 = b.a.last_name
return " ".format(field1, field2)
Then you can use binstance.pk
binstance.pk
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
do you want to print field1 and field2 using "a" attribute ?
– Atul Kumar
Sep 8 '18 at 10:05