如何使用来自foreignkey模型对象的django模板中的字段



models.py

class Position(models.Model):
positions = models.CharField(max_length = 200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.positions
class Candidate(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField('User Email')
mobile_no = models.CharField(max_length=10)
candidate_image = models.ImageField(null=False, blank=False, upload_to="candidate_images/")
description = models.TextField(null=True, blank=True)
votes = models.IntegerField(default = 0)
positionc = models.ForeignKey(Position, on_delete = models.CASCADE, related_name ='candidateobj')
def __str__(self):
return self.first_name

视图.py

def candidate_list(request):
candidate_list = Candidate.objects.get(pk=1)
return render(request, 'candidate_list.html', {
"candidate_list": candidate_list,
})

candidate_list.html

<div class="card-header"> {{ candidate_list.position.positions }} </div>

在这里我应该可以从"位置"模型中看到位置。但上面的代码没有任何内容。其他信息正确显示在candidate_list.html中。

我在谷歌上查了一下,发现一篇文章也提出了这个问题。Stackoverflow解决方案正是我认为的问题,我在代码中也做了类似的操作,但在html页面中没有得到任何东西。我是姜戈的新手。

您的语法有错误。引用CCD_ 1的字段被称为";位置c";而不是";位置";。

解决方案是:

{{ candidate_list.positionc.positions }}