Home > OS >  How do I use django templates to get a field from the parent object of a model?
How do I use django templates to get a field from the parent object of a model?

Time:01-07

I'm trying to create an interface where students can match with other students in the class for a group project based on shared interests and I have a queryset in a django view and from there I am able to use select_related to get the parent object and even print the fields in Anaconda Prompt (when running on local server) but I can't seem to get the field to show up in a template...what am I missing?

Here is the relevant part of my models file:

class Profile(models.Model):
    first_nm = models.CharField(max_length=100)
    last_nm = models.CharField(max_length=100)

class Potential(models.Model):
    user1 = models.ForeignKey(Profile, related_name='user1', on_delete=models.CASCADE)
    user2 = models.ForeignKey(Profile, related_name='user2', on_delete=models.CASCADE)

Here is the relevant part of my view:

def matches(request):
    my_user = request.user
    my_id = Profile.objects.get(slug=my_user)
    the_matches = Potential.objects.filter(Q(user1=my_id) | Q(user2=my_id)).all().select_related('user1','user2')
    print(the_matches.values())
    print(the_matches.values('user2__first_nm'))
    return render(request,'projects/matches_list.html', { 'matches':the_matches})

Here is the relevant part of the template:

{% for match in matches %}
     <div >
       <p>{{ match.user1__first_nm }}</p>
       <p>{{ match.user2__first_nm }}</p>
     </div>
{% endfor %}

In the template above, why does this not work?

Thanks in advance!

I have tried using the syntax above like:

<p>{{ match.user2__first_nm }}</p>

and when just printing to the console I get

<QuerySet [{'user2__first_nm': 'test_nm'}]>

from the second to last line in the view above but when I run locally, the html shows up with p tag with no contents. What am I doing wrong?

Thanks!

CodePudding user response:

Do not use __ in template, but use .

__ is only used when constructing QuerySets. In your template, you're accessing the Profile object, so to get an attribute from that object you use the syntax object.attribute.

Your code becomes:

{% for match in matches %}
     <div >
       <p>{{ match.user1.first_nm }}</p>
       <p>{{ match.user2.first_nm }}</p>
     </div>
{% endfor %}
  • Related