【问题标题】:Change a django form field's value after validation验证后更改 django 表单字段的值
【发布时间】:2012-01-24 03:50:43
【问题描述】:

我正在开发一个多面搜索系统。在搜索框下方,有一个带有选项的单选小部件:

O New search     O Within your results

当页面加载时,应该默认选择新搜索,所以我使用initial关键字。

我遇到的问题是,在用户选择New search 并进行查询后,我希望将默认值切换为Within your results,因为大多数搜索都是细化的。

所以我需要做的是更改用户提交的值,该值存储在 Django Form 中。

如何更改表单字段的值?验证已经发生,从我目前收集到的信息来看,request.GET 是不可变的(可能是件好事),我也无法更改 Form

【问题讨论】:

    标签: django django-forms faceted-search


    【解决方案1】:

    django推荐的修改request.GET的方式是call the copy method.

    mutable_get = request.GET.copy()
    mutable_get['search'] = 'within_results'
    

    您还可以在__init__ 表单中动态设置初始值,或者仅通过访问绑定的表单字段属性。

    form.fields['my_field'].initial = True
    

    哪一个有效取决于您构建表单的方式。

    【讨论】:

      【解决方案2】:

      只是一个想法,而不是破解用户输入,您可以仅在您有用于搜索的查询参数时显示该字段。

      这样,用户第一次“点击”视图时,他不会看到无用的无线电场。

      例如在这里,我将在表单的 __init__ 期间使用搜索参数将字段设置为隐藏并具有正确的初始值(您也可以执行 DrTysa 建议的操作,并在表单级别移动搜索检测,查看数据字典)

      searching = False
      if data.get('query'):
          searching = True
      form = SearchForm(data, searching=searching)
      

      【讨论】:

      • 这或多或少是我要走的路线。我忘记了最初不应显示单选按钮。不过,我并没有处理隐藏的表单——如果它是空白的,我可以暗示用户想要一个新的搜索。
      【解决方案3】:
      class MyForm(forms.Form):
          def __init__(self, data, *args, **kwargs):
              if 'do_search' in data: # or any other way to find out if there is an existing search
                  kwargs['initial'] = kwargs.setdefault('initial', {'your_radio': 'your_within_value'})
              super(MyForm, self).__init__(self, data, *args, **kwargs)
      

      【讨论】:

        猜你喜欢
        • 2014-09-28
        • 1970-01-01
        • 2016-03-30
        • 1970-01-01
        • 2013-09-03
        • 2017-02-28
        • 1970-01-01
        • 2011-02-24
        • 2016-04-08
        相关资源
        最近更新 更多