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

Time:01-11

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 >{{ 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.

CodePudding user response:

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.

CodePudding user response:

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

  • Related