Answer the question
In order to leave comments, you need to log in
How to implement autocomplete fields correctly?
Hello! Please help me figure it out.
I have a form with two fields. The first field is ChoiseField (user_characteristic), the second field is a simple Textarea (description). I'm trying to make it so that when a value is selected from the first field, the second field is auto-completed. I'm using jQuery UI autocomplete. Can you please tell me how to implement something like this?
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', 'autocomplete': 'off'})
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)
$("#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;
}
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question