我写了一段代码,用户可以从选择框中选择职业(老师,医生,飞行员等),如果他们的职业不在列表中,他们可以选择“其他”,然后写下他们的职业在下面的文本框中。
我可以成功检测到他们是否从下拉框中选择了“其他”,但无法弄清楚如何用“其他”字段中的数据填充“职业”字段。
if request.method == 'POST':
form = OccupationForm(request.POST, request.FILES, instance=request.user.occupation)
if form.is_valid():
# if user selected 'other' - get input from text field
if form['occupation'].value() == 'other':
# this doesnt work
#form_data = self.get_form_step_data(form)
#form.other = form_data.get('other', '')
#form.save()
return redirect('#')
#form.save()
#return redirect('#')
else:
form = OccupationForm(instance=request.user.occupation)
谢谢。
编辑: 缩短了模型。py
class Occupation(models.Model):
# I just realized, maybe this should be OneToManyField ??
user = models.OneToOneField(User, on_delete=models.CASCADE)
OCCUPATIONS = (
('teacher', 'Teacher'),
('doctor', 'Doctor'),
('other', 'Other'),
)
occupation = models.CharField('What is your job?', max_length=200, null=True, choices=OCCUPATIONS)
缩短表格。py
class OccupationsForm(forms.ModelForm):
other = forms.CharField(required=False, label='')
def clean(self):
cleaned_data = super().clean()
if cleaned_data.get('occupations') == 'other':
cleaned_data['occupations'] = cleaned_data.get('other')
return cleaned_data
class Meta:
model = Occupations
fields = ['occupations']
谢谢
答案 0 :(得分:0)
表单clean methods是验证和清除发送到表单的数据的地方,这包括可能更改数据的地方。
class OccupationForm(forms.ModelForm):
....
def clean(self):
cleaned_data = super().clean()
if cleaned_data.get('occupation') == 'other':
cleaned_data['occupation'] = cleaned_data.get('other')
return cleaned_data
现在您可以在form.save
之后直接调用form.is_valid
,因为clean
方法将清除/返回正确的数据