gpt4 book ai didi

ajax - Django - 基于验证的带有 "did you mean"提示的自定义小部件

转载 作者:行者123 更新时间:2023-12-01 04:20:16 25 4
gpt4 key购买 nike

我有一个基本模型:

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

现在,我想要的场景是:
  • 在网站上,我在“my_field”输入字段中输入一个值并点击提交按钮。
  • 如果值通过查找,我应该自动执行表单的操作。
  • 如果我得到多个可能的值,那么我应该将它们显示给用户并且不执行其他操作。
  • 如果我没有得到答案(空列表),我应该收到一条错误消息。

  • 一些附加要求:
  • 我希望无需重新加载页面即可显示“您的意思是”列表。
  • 如果用户单击其中一项建议,我想在不进行额外查找的情况下执行表单操作 - 该值已被检查。
  • 我想将所有逻辑保留在 View 之外,并将其保留在表单或模型中。这是必须的。
  • 我想避免在模板中硬编码 js 并尽可能将其推送到表单中。这不是必须的。

  • 所以我假设它会全部分布在这个字段验证和一个自定义小部件之间,该小部件将处理“你是不是要”列表呈现。我只是不能把它们放在一起。

    需要您的帮助:)

    编辑。广告。 2 要求。
    这是我描述的基本功能。在更高级的表单中,我希望此表单具有更多字段,因此应显示“您是指吗”列表以及所有其他字段错误(如果有)。然后单击提示只会将 my_field 的值设置为它的值,而无需重新加载表单。用户还必须更正其他错误,因此我无法立即执行表单操作。可能只有一些标志可以在这两个选项(“基本”和“高级”)之间切换。

    最佳答案

    1. I would prefer the "did you mean" list to be displayed without having to reload the page.


    创建自定义小部件,使用 JS 代码呈现,用于在用户输入时检查可能的值

    1. 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.


    同样,当点击该小部件时,应该只提交表单。

    1. 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 - 你仍然提出验证错误。

    1. 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com