我有一个带有下拉列表的 Django 表单,该表单正在动态填充 ajax 选择。表单类如下所示:
class SightingForm(ModelForm):
ajax_bird = forms.CharField(required=True, label="Bird", widget=forms.Select(attrs={'class': 'longdropdown chosenBirds', 'data-placeholder': 'Select a Bird'}, choices=DEFAULT_BIRDS) )
new_photo = forms.ImageField(required=False, label="Photo")
class Meta:
model = Sighting
fields = ('ajax_bird','count',)
def clean_ajax_bird(self):
ajax_bird = self.cleaned_data['ajax_bird']
abi = 0
try:
abi = int(ajax_bird)
bird = Bird.get_bird(abi)
if bird is None:
raise Exception
except Exception as ex:
raise forms.ValidationError("Please select a bird.")
return ajax_bird
def clean(self):
super(forms.ModelForm, self).clean()
try:
ab = self.cleaned_data['ajax_bird']
if int(ab) > 0:
bird = Bird.get_bird(int(ab))
self.ajax_bird.widget = forms.Select(attrs={'class': 'longdropdown chosenBirds', 'data-placeholder': 'Select a Bird'}, choices=((str(bird.id), str(bird.common_name),),))
return self.cleaned_data
except:
"""fail silently"""
在验证之前一切正常。如果页面上的任何其他内容未验证,则 ajax_bird 字段将不再填充用户选择(因为它是由 ajax 第一次生成的)。
在 clean 方法中,您可能会看到我正在尝试做的事情。我想根据 ajax 下拉菜单中选择的内容更改默认选项。有什么干净的方法可以做到这一点吗?