Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Django OneToOneField in templates?

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.

like image 504
lud0h Avatar asked Jul 13 '11 08:07

lud0h


People also ask

How do I get OneToOneField in Django?

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.

How do I access Django templates?

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.

How do I use Python code in Django template?

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.

How do I reuse a Django template?

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.


1 Answers

class B(models.Model):
    c = models.OneToOneField(A, related_name='b')
    d = models.DecimalField()

{{ a.b.d }}
like image 54
DrTyrsa Avatar answered Oct 12 '22 03:10

DrTyrsa