【发布时间】:2021-08-31 18:08:28
【问题描述】:
我正在尝试将外键选项添加到选择输入中,但不知道如何获取它。我想和使用 Django 生成的表单一样,但使用我自己的 HTML。 该表单用于创建新的“患者”。
这是我的患者模型中的外键:
ubication = models.ForeignKey(Ubication, on_delete=models.CASCADE)
supervisor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
这是患者表格:
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ['dni', 'first_name', 'last_name', 'birth', 'risk', 'status', 'ubication', 'supervisor']
widgets = {
'dni': forms.NumberInput(attrs={'class': 'form-control'}),
'first_name': forms.TextInput(attrs={'class': 'form-control'}),
'last_name': forms.TextInput(attrs={'class': 'form-control'}),
'birth': forms.DateInput(attrs={'class': 'form-control'}),
'risk': forms.CheckboxInput(attrs={'class': 'form-control'}),
'status': forms.Select(attrs={'class': 'form-select'}),
'ubication': forms.Select(attrs={'class': 'form-select'}),
'supervisor': forms.Select(attrs={'class': 'form-select'})
}
例如,这里我想将主管模型中的主管添加到患者模型中:
<select class="form-select" aria-label="Default select example" required name="supervisor" id="id_supervisor">
<option selected>Select supervisor</option>
{% for f in form.supervisor %}
<option value="{{f.id}}">{{f.first_name}}</option>
{% endfor %}
</select>
【问题讨论】:
标签: django django-models django-forms django-templates