Django-来自Model的动态表单

时间:2019-08-29 09:38:22

标签: python django django-models django-forms

我正在尝试实现动态形式,该形式显示数据库选择中的一些选项。该表格应显示给定律师编号的CASES名称(即“选项1”)。

例如:用户选择ID = 6的律师,并且该Law_id在LawyersSpec模型中具有“选项1”和“选项2”。在表单中,我只想显示“选项1”和“选项2”作为可能的选项。我该如何实现?

我尝试使用动态表格来覆盖 init

中的queryset
    def __init__(self, *args, lawyer_id, **kwargs):
        super().__init__(*args, **kwargs)

        lawyer_spec = LawyersSpec.objects.filter(lawyer_id=lawyer_id)

但是它从数据库返回记录的全名,不仅是选择值。

models.py

class LawyersSpec(models.Model):
    lawyer_id = models.ForeignKey('MyUser', on_delete=models.PROTECT)
    lawyer_spec = models.SmallIntegerField(choices=CASES)

CASES = (
    (1, 'Option 1'),
    (2, 'Option 2'),
    (3, 'Option 3'),
    (4, 'Option 4'),
    )

编辑: 我只想在spec字段中显示可用于给定律师ID的选项(“选项1”,“选项2” ...)。

forms.py

class MakeAppointmentForm(forms.Form):
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)
    spec = forms.ChoiceField()

1 个答案:

答案 0 :(得分:1)

在表单的初始化方法中,重置spec字段的选择:

# after super().__init__
lawyer_specs = LawyersSpec.objects.filter(lawyer_id=lawyer_id)
choices = ((spec.lawyer_spec, dict(CASES)[spec.lawyer_spec]) for spec in lawyer_specs)
self.fields['spec'].choices = choices

不要忘记从模型中导入CASES。在CASES类中包含LawyerSpec会更容易,那么您可以只引用LawyerSpec.CASES