Display fields of a Foreignkey relation in the template

Asked

Viewed 29 times

0

Save Devs... I need a help to display the fields of a table that is Foreignkey relationship in a Template.

models

class IEIS (models.Model):

    nome = models.CharField (max_length=25,null=False, blank=False)
    revisao = models.CharField (max_length=20,null=True, blank=True)
    pit = models.ForeignKey(PIT, related_name='pit', on_delete=models.CASCADE, verbose_name= 'PIT - Plano de Inspeção e Teste')

class PIT(models.Model):

    nome = models.CharField(max_length=50, null=False, blank=False)
    fluido = models.ManyToManyField(Fluido, related_name='fluido', blank=True, unique=False)

In the IEIS class I have the PIT field as FK. I need to display in the IEIS view template, some PIT class fields.

views

def view_ieis(request, pk):
    ieis = IEIS.objects.get(pk=pk)
    especs = ieis.especificacao.all()
    fluidos = ieis.fluido.all()
    pits = PIT.objects.get(pk=pk)
    return render(request, 'ieis/view.html', {'ieis': ieis, 'especs': especs, 'fluidos': fluidos, 'pits': pits,})``` 


**ieis.html**



PIT
    </tr>
  </thead>
  <tbody>
    <tr>

        {% for pit in ieis.pits.all %}
            {{ pit }} {{ pit.nome }}
        {% endfor %}

    </tr>
  </tbody>
```

Thanks in advance for all the attention, suggestion and help dedicated!

1 answer

0

Try it this way:


class PIT(models.Model):
    nome = models.CharField(max_length=50, null=False, blank=False)
    fluido = models.ManyToManyField(Fluido, related_name='fluido', blank=True, unique=False)
    
    def __str__(self):
        return self.nome
 
class IEIS (models.Model):
    nome = models.CharField (max_length=25,null=False, blank=False)
    revisao = models.CharField (max_length=20,null=True, blank=True)
    pit = models.ForeignKey(PIT, related_name='pit', on_delete=models.CASCADE, verbose_name= 'PIT - Plano de Inspeção e Teste')
    
    def __str__(self):
        return self.nome
    
    # Como só quer mostrar no contexto os dados de PIT não precisaria implementar o __str__ no IEIS. 

And now in the template: just leave the 'for pit in pits.all'; and obviously it will repeat the name of the PIT data because the two tags return the same value.

    </tr>
  </thead>
  <tbody>
    <tr>

        {% for pit in pits.all %}
            {{ pit }} {{ pit.nome }}
        {% endfor %}

    </tr>
  </tbody>
  • This inversion was at the time to assemble the question. The code is correct. I also cannot understand why it does not return the fields of the PIT table. It takes as object and not the fields.

  • I updated the answer, maybe it’ll help!

  • It helped yes, thank you. I took a line with your and other suggestions and managed to heal.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.