我有一个基本模型:
class MyModel(models.Model):
my_field = models.CharField()
我有这个模型的基本形式:
class MyFrom(forms.ModelForm):
class Meta:
model = MyModel
而且我有一个执行基本查找的函数(实际上要复杂得多,正则表达式等不会这样做):
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
现在,我想要的场景是:
一些附加要求:
所以我假设它会全部分布在这个字段验证和一个自定义小部件之间,该小部件将处理“你是不是要”列表呈现。我只是不能把它们放在一起。
需要您的帮助:)
编辑。广告。 2 要求。
这是我描述的基本功能。在更高级的表单中,我希望此表单具有更多字段,因此应显示“您是指吗”列表以及所有其他字段错误(如果有)。然后单击提示只会将 my_field 的值设置为它的值,而无需重新加载表单。用户还必须更正其他错误,因此我无法立即执行表单操作。可能只有一些标志可以在这两个选项(“基本”和“高级”)之间切换。
最佳答案
- I would prefer the "did you mean" list to be displayed without having to reload the page.
创建自定义小部件,使用 JS 代码呈现,用于在用户输入时检查可能的值
- 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.
在表单上,您将使用 clean() 方法来验证所有内容。例如,如果一些虚假数据通过从 p 提交。 2 - 你仍然提出验证错误。
- I want to avoid hardcoded js in the template and push it into the form if possible. It's not a must.
使用自定义小部件解决,details .
关于ajax - Django - 基于验证的带有 "did you mean"提示的自定义小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2147618/