I have a Django form. One of the fields (monitoring_method) uses an autocomplete-light widget that filters the results based on the entry in another field (database_type). Is there any way to get the user-entered value in the database_type field before it is submitted? I would know how to do it with AJAX (or could figure it out) but I'm not sure--and maybe this is my real question--how to incorporate AJAX with autocomplete.
class MonitoringMethodAutocomplete(autocomplete_light.AutocompleteBase):
autocomplete_js_attributes = {'placeholder': 'Choose a database type to enable monitoring method selection'}
def choices_for_request(self):
q = self.request.GET.get('q', '')
db_type = self.request.POST.get('database_type')
# if not db_type:
# return []
monitoring_methods = Database.objects.values_list('monitoring_method', flat=True)
return monitoring_methods.filter(database_type__exact=db_type,
name__icontains=q).distinct()
def choices_for_values(self):
return []
EDIT:
So, I originally figured that what I was trying to do would not be possible, but then I realized that the q
variable is doing something similar... so why isn't db_type
working?
Yay.
<script type="text/javascript">
$(init);
function init() {
var database_form = $('.asset-form');
var db_type_field = $('#id_database_type');
database_form.data('db_type', db_type_field.val());
db_type_field.on('change', function() {
var db_type = db_type_field.val();
console.log(db_type);
$('.autocomplete-light-text-widget').yourlabsAutocomplete().data = {'database_type':db_type};
});
// disable enter key from posting form
$('#id_database_type').keypress( function(event) {
if (event.which == 13) {
event.preventDefault();
};
});
}
</script>