【发布时间】:2020-01-02 13:28:29
【问题描述】:
我正在尝试实现显示数据库选择中的一些选项的动态表单。表格应显示给定律师 ID 的案例名称(即“选项 1”)。
例如:用户选择了 ID = 6 的律师,而这个律师的 ID 在 LawyersSpec 模型中有“选项 1”和“选项 2”。在表单中,我只想显示“选项 1”和“选项 2”作为可能的选项。我怎样才能做到这一点?
我尝试过在 init
中覆盖查询集的动态表单 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'),
)
编辑: 我只想在规范字段选项中显示(“选项 1”、“选项 2”...),这些选项可用于给定的律师 ID。
forms.py
class MakeAppointmentForm(forms.Form):
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
spec = forms.ChoiceField()
【问题讨论】:
-
如果表单字段是
ChoiceField,只需使用choices=...进行初始化,您将在其中放入元组列表,例如基于LawyersSpec.objects.filter(lawyer_id=lawyer_id).values('lawyer_spec')。 -
但是由于您没有显示表单或您将使用它保存的值(这与您显示的内容不同,因此是
choices的元组列表)它是很难在我们的回答中更具体。 -
我添加了forms.py,基本上我想准确显示CASES值中的内容(“选项1”等)
标签: python django django-models django-forms