我在下面的django
中创建了模型:
模型
class TermPolicyPeriod(models.Model):
term = models.IntegerField()
start_term = models.DateField(auto_now_add=False, blank=True, null=True)
end_term = models.DateField(auto_now_add=False, blank=True, null=True)
term_end = models.BooleanField(default=False)
class TermPolicyDetails(models.Model):
branch = models.CharField(max_length=150)
branch_code = models.CharField(max_length=3)
class_type = models.CharField(max_length=255)
week_type = models.CharField(max_length=10)
students_per_coach = models.IntegerField()
start_class_time = models.TimeField(auto_now_add=False, blank=True)
end_class_time = models.TimeField(auto_now_add=False, blank=True)
duration_class_time = models.TimeField(auto_now_add=False, blank=True)
notes = models.TextField(max_length=350, null=True)
foreign_key_term_end = models.ForeignKey(TermPolicyPeriod, on_delete=models.CASCADE)
观看次数
...
args = {
# Term Policies - Period
'new_term_policy_period_form': new_term_policy_period_form,
'term_period_policy_page_data': term_period_policy_page_data,
'edited_tpp': edited_tpp,
# Term Policies - Details
'new_term_policy_details_form': new_term_policy_details_form,
'term_policy_details_page_data': term_policy_details_page_data,
'edited_tpd': edited_tpd,
}
return render(request, 'static/html/home.html', args)
在我要在html
中创建的表单中,我希望foreign key
自动链接到TermPolicyPeriod pk
。我一直在搜索,但是不确定syntax
应该如何写。我想到了
<form>
{% csrf_token %}
{% for pp in new_term_policy_period_form %}
{% for pd in new_term_policy_details_form %}
{% set pd.foreign_key_term_end_id = pp.pk %}
{% endfor %}
{% endfor %}
...
<button type="submit">submit</button>
</form>
在html中是否可能出现这种情况?
答案 0 :(得分:0)
为了正确设置外键,您应该在视图中的TermPolicyPeriod
中创建新的form.is_valid()
实例,然后将TermPolicyDetails
的外键设置为该实例的pk。