我有一个无趣的模型。其中一个模型字段occupation是一个表的外键,该表包含一个很长的选项列表。问题是对于更新,通过crispy呈现的呈现表单没有将焦点设置为存储值(在<select><option...>
代码中将其标记为选定选项)。相反,它显示了空的选择。我看到初始值确实指向数据库记录的id。
为了让这个过程更“有趣”一点,我想把occupation.to_field_name
改为occupation.code
(一个字符域)。我一直futzing与形式的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']))
1条答案
按热度按时间jpfvwuh41#
我想出了一个解决这个问题的方法,在document.ready上添加一个js函数,并在上下文中传递答案。这是一个简单的循环,通过选择选项,然后添加一个选定的属性到正确的选项。
我仍然想知道如何正确地使用django对象来做到这一点。似乎我做错了什么,或者没有正确初始化窗体上的小部件或字段。