Hi!
I have a basic model :
class MyModel(models.Model):
my_field = models.CharField()
I have a basic form for this model :
class MyFrom(forms.ModelForm):
class Meta:
model = MyModel
And I have a function that does a basic lookup (a lot more complex in reality, regex etc. won't do) :
POSSIBLE_VALUES = ['aa', 'bb', 'cc', 'dd']
def lookup(some_value):
if some_value in POSSIBLE_VALUES:
# the value is OK, return a string
return some_value
else:
# constructs the 'did you mean' list of suggestions
didyoumean = [pv for pv in POSSIBLE_VALUES if pv in some_value]
# returns a list which might be empty
return didyoumean
Now, the scenario that I want is:
- On the site I enter a value in the "my_field" input field and hit submit button.
- If the value passes the lookup I should automatically perform the form's action.
- If I get multiple possible values then I should display them to the user and no other action is performed.
- If I get no answers (an empty list) I should get an error message.
Some additional requirements:
- I would prefer the "did you mean" list to be displayed without having to reload the page.
- If a user clicks on one of the suggestions I want to perform the form's action without an additional lookup - the value has already been checked.
- I want to keep all the logic outside the view and keep it in the form or in the model. This is a must.
- I want to avoid hardcoded js in the template and push it into the form if possible. It's not a must.
So I assume that it would all be distributed between this fields validation and a custom widget that would handle the "did you mean" list rendering. I just can't put it all together.
Your help is required :)
EDIT. Ad. 2 in requirements. That is a basic feature I described. In a more advanced one I want this form to have more fields and so the "did you mean" list should be displayed along with all other fields errors (if any). Then clicking on a hint would just set the my_field's value to it's value without reloading the form. A user would have to correct other errors as well so I can't go to form's action right away. Might there be just some some flag to switch between those two options ("basic" and "advanced").