【问题标题】:Get form values (foreign key field) in django在 django 中获取表单值(外键字段)
【发布时间】: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


    【解决方案1】:

    我相信您希望在其中用户根据可用的主管之一选择主管的选择字段,对吗?

    您可以在表单脚本中创建选项。

    PatientForm 上执行以下操作:

    # SUPERVISORS is the model where the supervisors are stored in your code
    # you will have to modify it
    from .models import SUPERVISORS
    
    CHOICES = [ (supervisor.id, supervisor.get_full_name())
                for supervisor in SUPERVISORS.objects.all() ]
    
    class PatientForm(forms.ModelForm):
       supervisor = forms.ChoiceField(choices=CHOICES)
          class Meta:
          # leave the rest as is
    
    

    如果您想对此进行调整,您可以获取更多信息here

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 2018-11-28
      • 2018-11-18
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2010-10-11
      相关资源
      最近更新 更多