I have the following scenario.
class A(models.Model):
a = models.IntegerField()
class B(models.Model):
c = models.OneToOneField(A)
d = models.DecimalField()
In my templates, I have a list of objects A. In my template how do I access the attribute "d" from my template?
Thanks.
Accessing OneToOneField Model fields in Django TemplatesGet all the objects of the model 'Contact' in your views.py file. And pass this to the template. Now, go to your HTML template and add this code.
To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.
You cannot use python code in django template. This is by design, Django's idea of template is to isolate the presentation logic from the programming code.
The most flexible way to reuse template fragments is to define an inclusion_tag. You can pass arguments to your custom tag, process them a bit in Python, then bounce back to a template. Direct inclusion only works for fragments that don't depend on the surrounding context.
class B(models.Model):
c = models.OneToOneField(A, related_name='b')
d = models.DecimalField()
{{ a.b.d }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With