在我的元素中,Profile
模型与Education
实例有Foreign Key
关系。这是我的模型:
class Profile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
full_name = models.CharField(max_length=30, null=True, blank=True)
education = models.ForeignKey(Education, on_delete=models.SET_NULL, null=True, blank=True, related_name="education")
class Education(models.Model):
degree = models.CharField(max_length=100, null=True, blank=True)
school = models.CharField(max_length=100, null=True, blank=True)
edu_start_date = models.DateField(null=True, blank=True)
edu_end_date = models.DateField(null=True, blank=True)
def __str__(self):
return str(self.degree)
现在,使用 Django ListView
,我无法显示外键的数据。我的观点:
class EducationView(CreateView):
form_class = EducationForm
pk_url_kwarg = 'pk'
template_name = "profile_settings.html"
class EducationList(ListView):
model = Profile
queryset = Profile.objects.all()
context_object_name = 'object'
pk_url_kwarg = 'pk'
template_name = "profile_settings.html"
模板
{% for obj in profile.education.all %}
<div class="col-lg-12">
<h2>{{ obj.degree }}</h2>
<br>
<div>
{{ obj.school }}
</div>
</div>
<br>
{% endfor %}
教育表单将数据保存到数据库,但我无法使用模板代码获取它。
注意:我对 CreateView 和 ListView 使用单一模板。
最佳答案
在 ListView 中,您将 context_object_name 指定为“object”。所以在模板内部,上下文是指一个对象。
所以代码看起来像
{% for each_profile in object %}
{% for obj in each_profile.education.all %}
<div class="col-lg-12">
<h2>{{ obj.degree }}</h2>
<br>
<div>
{{ obj.school }}
</div>
</div>
<br>
{% endfor %}
{% endfor %}
关于javascript - 如何访问 Django 模板中的外键? (列表显示),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54938545/