Answer the question
In order to leave comments, you need to log in
How to create autocomplete for fields?
Hello! Please help me figure it out.
In my Django app, I have a modal window with a form that has three fields. I'm trying to use autocomplete for the first field using JQuery UI Autocomplate . Used the following code but doesn't work. Please tell me where I made a mistake and how to fix it? You also need to use the first field after the user selects the value to autocomplete the second field based on the first field. How to do this kind of autocomplete? In the first field, you need to autofill with values from user_class and, depending on this, put the value from user_symbol in the second field.
models.py:
class UserDictionary(models.Model):
user_class = models.CharField(_('Class'), max_length=250)
user_symbol = models.CharField(_('Symbol'), max_length=250)
user_name = models.TextField(_('Description'))
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('user_class', 'user_symbol', 'user_name')
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
self.fields['user_class'].widget = TextInput(attrs={'id': 'user-class'})
self.fields['user_symbol'].widget = TextInput(attrs={'id': 'user-symbol'})
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
$(function() {
$("#user_class").autocomplete({
source: "/user_autocomplete/",
minLength: 2
});
});
url(r'^user_autocomplete/$', user_autocomplete, name='user_autocomplete'),
def user_autocomplete(request):
if request.is_ajax():
word = request.GET.get('term', '')
users = UserDictionary.objects.filter(user_class__icontains=word)
results = []
for user in users:
user_json = {'label': user.user_class, 'value': user.user_class}
results.append(user_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
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