我有2个字段的表单。
第一个字段user_characteristic
为СhoiseField
,第二个字段description
为简单Textarea
。
当用户从第一个字段中选择一些值时,我想要自动编译第二个字段。
我使用JQuery UI自动完成功能。在下面你可以看到我的代码。我错在哪里?
forms.py:
RequirementForm(forms.ModelForm):
class Meta:
model = Requirement
fields = ('user_characteristic', 'description',)
widgets = {
'user_characteristic': forms.Select(attrs={'class': 'form-control', 'id': 'user-characteristic',}),
}
def __init__(self, *args, **kwargs):
super(RequirementForm, self).__init__(*args, **kwargs)
self.fields['user_characteristic'] = forms.ChoiceField(
choices=[(x.user_symbol, x.user_class) for x in UserCharacteristic.objects.all()],
)
self.fields['description'].widget = Textarea(attrs={'class': 'form-control', 'id': 'description',})
views.py:
def requirement_autocomplete(request):
if request.is_ajax():
word = request.GET.get('term', '')
user_characteristics = UserCharacteristic.objects.filter(user_class__icontains=word)
results = []
for user_characteristic in user_characteristics:
user_characteristic_json = {
'id': user_characteristic.id,
'label': user_characteristic.user_class,
'value': user_characteristic.user_class,
'user_characteristic_description': user_characteristic.user_symbol + ' – Варианты использования для роли ' + user_characteristic.user_description
}
results.append(user_characteristic_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
的javascript:
$("#user-characteristic").autocomplete({
source: "/requirement_autocomplete/",
minLength: 0,
select: function( event, ui ){
$("#user-characteristic").val(ui.item.value);
$("#description").val(ui.item.user_characteristic_description);
return false;
}
});