[Answer]-Django: How to get a named related field in a template

1👍

In the Django template language, the dot notation can be a dictionary lookup. E.g. {{ foo.bar }} will be treated as foo['bar'].

Using Python we can transform this into a function call of sorts…

class MyGetter(object):

    def __getitem__(self, item):
        return "Trying to get {}".format(item)

def home(req):
    return render(req, "hello.html", {"stuff": MyGetter()})

And in hello.html, if you have something like this:

<p>{{ stuff.foo }}</p>

You’ll see the message “Trying to get foo” appear on the page. Basically all you need to do is modify the body of __getitem__ to suit your purposes. (And, of course, come up with appropriate names for everything.)

There are other ways to do this (i.e. __getattr__) but I think using __getitem__ is the most clear.

Furthermore, you could also use custom template tags/template filters if you like. It’s all up to you. This is how I would do it, since it seems to involve the fewest number of moving parts.

TL;DR

Try this:

class FieldReader(object):

    def __init__(self, bug):
        self.__bug = bug

    def __getitem__(self, item):
        return self.__bug.scrublines.get(field=item).value

In your template, you can use

{{ field_reader.field1 }}

to get the value of field1 for whatever Bug you sent to the FieldReader constructor.

0👍

You could use a nested loop to iterate over the related scrubs of each bug.

{% for scrub in bug.scrublines.all() %}
    <td>scrub</td>
{% endfor %}

Or use scrub.field if you only want print a specific field of the scrub.

** edit **

Because of your models, there will have many scrubs for a bug. So the right way to access them is using the defined related_name (scrubslines) and and the all method

Leave a comment