Maicmi Maicmi - 1 year ago 61
Python Question

May I display the field from other table in the template in Django 1.10?

May I display the field from other table in the template in Django 1.10?

I have 3 tables as the following

import datetime

from django.db import models
from django.forms import ModelForm
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible

class Group(models.Model):
group_name = models.CharField(max_length=255)
no_of_monk = models.IntegerField()
def __str__(self):
return self.group_name
class Meta:
ordering = ['id']

class Tbl_Province(models.Model):
province_code = models.CharField(max_length=2)
province_name = models.CharField(max_length=150)
geo_id = models.IntegerField()
def __str__(self):
return self.province_name

class Contact(models.Model):
group = models.ForeignKey(Group, on_delete=models.CASCADE)
order = models.IntegerField()
name = models.CharField(max_length=255, db_index=True)
description = models.TextField(blank=True)
amount = models.DecimalField(max_digits=10, decimal_places=2)
confirm = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
province = models.ForeignKey(Tbl_Province, on_delete=models.CASCADE)
def __str__(self):
class Meta:
ordering = ['order', 'province']

and I would like to display tbl_province.province_name where in the following template, is it possible?

{% for contact in group.contact_set.all %}
<td width="10%" class="table-text"><div><strong>{{ forloop.counter0|mod:5|add:1 }}</strong></div></td>
<td width="10%" class="table-text"><div>{{ forloop.counter }}</div></td>
<td width="10%" class="table-text"><div>{{ contact.order }}</div></td>
<td class="table-text"><div>{{ }}</div></td>
{% if contact.province_id %}
<td class="table-text"><div>{{ **Want to display tbl_province.province_name where here** }}</div></td>
{% endif %}
<td width="13%" class="table-text"><div><input type="text" name="ord" id="con-ord" class="form-control" value="{{ contact.amount|intcomma }}"></div></td>
<td width="10%" class="table-text"><div>บาท</div></td>
<form action="{% url 'contribution:contactdel' %}" method="POST">
{% csrf_token %}
<button type="submit" id="delete-group" class="btn btn-danger">
<i class="fa fa-btn fa-trash"></i> Delete
{% endfor %}

Answer Source

Templates don't have the access to the database, so they can't execute a query (and that's basically what you want)

However, I can see that you have a foreign key to Tbl_Province in Contact and you can use that instead - just write {% contact.province.province_name %} (if I understand correctly what you're trying to achieve)

If you need anything more exotic, you'll have to execute your query inside the view function, and then pass it to template context.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download