我有一个无趣的模型。模型字段之一“职业”是包含一长串选项的表的外键。问题是更新时,通过脆皮渲染的渲染表单没有将焦点设置到存储的值(将其标记为
<select><option...>
代码中的选定选项)。相反,它显示空选择。我看到初始值确实指向数据库记录的id。
为了让这个更“有趣”,我想将
occupation.to_field_name
更改为 occupation.code
(charfield)。我一直在研究表格的init
,如下所示。我可以将选项值转换为我想要的形式,但我无法让表单将存储的值呈现为选定的值(并呈现为字段的选定值)。
我该怎么做?我必须通过 JS 来完成还是我的表单做错了什么?谢谢。
class Meta:
model = TutorOptionalServiceAndDemographics
fields = ['highest_degree',
'country_of_birth',
'immigrant',
'us_citizen',
'employment_status_at_enrollment',
'occupation',
'employer_name',
'referral',
]
labels = {
'highest_degree': 'Highest degree/diploma earned',
'us_citizen': 'US Citizen:',
'immigrant': 'Immigrant:',
'country_of_birth': 'Country of Birth:',
'employment_status_at_enrollment': 'Employment status at time of registration:',
'occupation': 'Occupation:',
'employer_name': 'Employer Name:',
'referral': 'Referred by or heard about the program from source:',
}
help_texts = {
'employment_status_at_enrollment': '',
'referral': 'Select all that apply',
}
yes_no = [('True', 'Yes'), ('False', 'No')]
widgets = {
'immigrant': HorizontalRadioSelect(choices=yes_no),
'us_citizen': HorizontalRadioSelect(choices=yes_no),
}
def __init__(self, *args, **kwargs):
super(TutorOptionalForm, self).__init__(*args, **kwargs)
# futzing goes here
self.helper = FormHelper(self)
self.helper.attrs['autocomplete'] = 'off'
self.helper.form_id = 'id-gather-name'
self.helper.form_class = 'form-horizontal'
self.helper.form_method = 'post'
# self.helper.form_action = ''
self.helper.label_class = 'col-5'
self.helper.field_class = 'col-6'
self.helper.form_tag = False
self.helper.layout = Layout(
'highest_degree',
'country_of_birth',
InlineRadios('immigrant'),
InlineRadios('us_citizen'),
'employment_status_at_enrollment',
'occupation',
'employer_name',
'referral',
)
# for i in self.fields['occupation']._queryset:
# print(f"i is {i} {i.id}")
initial_value = [x for x in self.fields['occupation']._queryset if x.id == self.initial['occupation']]
print(f"initial value is {initial_value[0].code}")
self.fields['occupation'].initial = initial_value[0].code
self.fields['occupation'].to_field_name = 'code'
pprint(vars(self.fields['occupation']))
# print("widget")
# pprint(vars(self.fields['occupation'].widget))
# try:
# actual_occupation = Occupation.objects.get(id=29)
# this is a hardcoded example just trying to figure out what's happening
# self.fields['occupation'].initial = actual_occupation.code
# except Occupation.DoesNotExist:
# self.fields['occupation'].initial = ""
# print(f"after ")
# pprint(vars(self.fields['occupation']))
我通过在 document.ready 上添加一个 js 函数并在上下文中传递答案来解决这个问题。这是一个简单的循环,遍历选择选项,然后将选定的属性添加到右侧选项。
我仍然想知道如何仅使用 django 对象正确完成此操作。看来我做错了什么或者没有正确初始化表单上的小部件或字段。