簡體   English   中英

html模板中的django外鍵表字段

[英]django foreign key table fields in html template

我有兩個表(文章、評論)使用外鍵關聯一對多關系。 我想要 html 模板列表和表中的一些字段,但我創建的文章不起作用,這里是代碼:

模型.py

class article(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True)
    last_name = models.CharField(max_length=254)
    age = models.CharField(max_length=254)

    def __unicode__(self):
        return str(self.id)


class comment(models.Model):
    field_1 = models.CharField(max_length=100, blank=True, null=True)
    field_2 = models.CharField(max_length=254)
    field_3 = models.CharField(max_length=254)
    field_fk= models.ForeignKey('article', blank=True, null=True)

    def __unicode__(self):
        return str(self.id)

視圖.py

def index(request):
    apps = article.objects.all()
    comments = comment.objects.all()
    return render(request, 'index.html', {'apps':apps,'comments':comments})

html 模板:

{% for b in apps %}
<p>{{ b.field_1 }}</p>
<p>{{ b.field_2 }}</p>
<p>{{ b.field_3 }}</p>
      {% for c in b.field_fk.comments %}
    <p>{{ c.name }},{{ c.last_name}},{{ c.age}}</p>
          {% endfor %}
{% endfor %}

在我的模板示例中,不顯示namelast_nameage為空段落

您不能僅使用.comments訪問評論。 使用modelname_set。 在您的情況下,將為comments_set 您的for循環將如下所示:

{% for c in b.field_fk.comment_set.all %}
    <p>{{ c.name }},{{ c.last_name}},{{ c.age}}</p>
{% endfor %}

另外,您沒有循環使用正確的模型。 apps設置為Article,但是在您的模板中,您使用的是Comment字段(field_1,field_2 ...)。 第一部分應該是:

{% for article in apps %}
    <p>{{ article.name}}</p>
    <p>{{ article.last_name}}</p>
    <p>{{ article.age}}</p>
...

由於文章是主循環,因此您無需使用外鍵。 循環應直接使用comment_set:

{% for comment in b.comment_set.all %}
    <p>{{ comment.field_1 }},{{ comment.field_2 }},{{ comment.field_3}}</p>
{% endfor %}

使用此代碼

意見.py:

def index(request):
    comments = comment.objects.all()
    return render(request, 'index.html', {'comments':comments})

HTML模板:

{% for b in comments %}
<p>{{ b.field_1 }}</p>
<p>{{ b.field_2 }}</p>
<p>{{ b.field_3 }}</p>
<p>{{ b.field_fk.name }},{{ b.field_fk.last_name}},{{ b.field_fk.age}}</p>
{% endfor %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM