Could not parse the remainder: '{%get(gender='F')%}.fullname' from 'x.parent.{%get(gender='F')%}.fullname'

38 views Asked by At

I have a problem with getting a data in template. I am writing code in python file its working.

  students = Student.objects.all()
  for x in students:
    print(x.parent.get(gender='M').fullname)

It gets me Parent Fullname, but when i write it in template like:

{% for x in students %}
  <td class="small d-none d-xl-table-cell  text-center">{{ x.parent.{%get(gender='F')%}.fullname }}</td>
{% endfor %}

it gets me Could not parse the remainder: '{%get(gender='F')%}.fullname' from 'x.parent.{%get(gender='F')%}.fullname' error. I tried write it like {{ x.parent.get(gender='F').fullname }} but i get same error

Same code working in python file but not working in template.

2

There are 2 answers

0
willeM_ Van Onsem On BEST ANSWER

You can't do that: Django's template language is deliberately limited to prevent people from writing business logic in the template.

You can define this in the Student model:

class Student(models.Model):
    # …

    @property
    def mother(self):
        return self.parent.get(gender='F')

    @property
    def father(self):
        return self.parent.get(gender='M')

Then you use:

{{ x.mother }}

in the template.


Note: The related_name=… [Django-doc] is the name of the manager to fetch the related objects in reverse. Therefore normally the related_name of a ForeignKey or ManyToManyField is plural, for example parents instead of parent.

0
NixonSparrow On

You cannot include {% %} bracket inside {{ }} bracket. You cannot simply use all Pythonish logic inside templates. Template engine can process only some simple things. For more complicated logic you can use custom tags, but first read: Django DOCS