I want to build an autocomplete form in a Django webapp. I have already been able to do the search bar where I query my MongoDB database but how can I add an autocomplete? I tried to adapt an official tutorial that does it with Javascript:
Even when I have autocomplete="nope" the first search bar still shows up the default autocomplete by chrome and doesn’t show up the one I built in MongoDB. The second doesn’t show up anything, even when I link the id to the script.
Hi @Mike_MPC, my apologies for the late reply here, but I hope this message finds you well.
I re-ordered my response because one was long.
I noticed a couple things about your snippet and thought a few bits of information could be helpful.
The second detail I would point out is the minLength=2 line. I think that should be minLength: 2. It is a key value pair in the object that is the parameter/argument of the autocomplete function, along with source and select.
First, here is a repo containing a hacked together Flask app I forked to port its search functionality to Atlas Search. It’s not exactly Django, which adds some more constructs, but it’s similar so it could be helpful. There’s even an example index definition for autocomplete in the README. Be sure you have set that autocomplete index up in Atlas, otherwise it work work.
Many thanks for your answer Marcus, no worries of being late. I was away for a few day as well.
Many thanks for your resource and for pointing out the error with minLength, I corrected it but it didn’t launch the autocomplete. So the error must be somewhere before. I’m reviewing my code and I will dive into your GitHub as long as I am sure the error isn’t from my side.
I am now reviewing my views.py which contains the query to MongoDB, I don’t know if it is realted to the autocomplete triggering. I guess not, but in such a case here it is:
The findone query worked, without triggering the autocomplete, the aggregate doesn’t so I’m reviewing it at the moment. If it doesn’t work I will redisign that with your example.
Ahh, herein lies the issue @Mike_MPC. Unfortunately, autocomplete does not support positional paths (note: position 0 in the Results array). For this query to work, you would need to unwind the results array if possible. You have a few options in triggers and materialized views via $merge.
Let me know if that fixes the issue. You could test by simply changing the path to another field that is already a non-enumerable field.
Thanks for that info @Marcus , I just created a non-enumarable field for all documents to deal with this positional path issue. I don’t have any error anymore but it doesn’t trigger the autocomplete either:
Okay thanks @Marcus , that make sense. I guess I need to create a new function. But I’ve looked at your code and I didn’t understand how it was triggered.
Indeed, if getrestaurants() is triggered by the find-restaurants submit action button. I don’t know about suggest_restaurants().