Django-在基于GET参数的搜索表单上设置复选框的更好方法



我已经做了很多搜索,但似乎没有在任何地方解决这个特定的表单创建品牌。

我正在创建一个搜索页面,该页面在数据库中查询属性等于或高于给定阈值的所有元素的集合。现在我有一个简单的表单,它有5个属性,每个属性有5个阈值,每个阈值都有自己的复选框,即

attrib_1 X threshold 1 X threshold 2 X threshold 3 X threshold 4 X threshold 5
attrib_2 X threshold 1 X threshold 2 X threshold 3 X threshold 4 X threshold 5  
... etc ...

HTML看起来像这样:

  <div class= "form-inline">
    <label>Attribute 1</label>
    <label class="checkbox inline">
      <input type="checkbox" name="attrib 1" value="1"> Very Negative
    </label>
    <label class="checkbox inline">
      <input type="checkbox" name="attribt 1" value="2"> Negative
    </label>
    <label class="checkbox inline">
      <input type="checkbox" name="attrib 1" value="3"> Nonfactor
    </label>
    <label class="checkbox inline">
      <input type="checkbox" name="attrib 1" value="4"> Positive
    </label>      
    <label class="checkbox inline">
      <input type="checkbox" name="attrib 1" value="5"> Very Positive
    </label>
  </div>

然后,我使用GET参数中的信息搜索数据库。当我显示搜索结果时,有什么优雅的方法可以确保复选框反映搜索查询?我希望用户会选中一些框,查看结果,然后再选中一些框来完善搜索,我不希望他们每次提交搜索时都必须重新检查所有框。

我已经考虑了几种方法。我可以对每个复选框使用if/else语句,并适当地填充checked属性。这是可行的,但看起来不雅,不太干燥,并且会导致一个非常复杂的模板。或者,在视图中,我可以创建一个数据结构(列表或元组列表,可能是列表的dict),它将为每个复选框"checked"或空字符串。这将产生一个更干净的模板,但我怀疑有一种更合适的Django/Python方法可以做到这一点。我也考虑过一种定制的形式,但这似乎是想把一个方形的钉子放在一个圆孔里。

那么,有什么优雅的方法可以确保根据GET参数正确检查搜索表单上的复选框呢?

我假设您是通过刷新而不是AJAX返回页面。在这种情况下。。。

我假设(根据Django标准)您已经将所有这些复选框作为Django表单的一部分。在这种情况下,您可以向表单传递一系列参数(我建议使用字典),其中包含所有复选框的初始值。

class SearchQuery(forms.form)
#Adding an init will allow us to pass arguments to this form In
# This case, a single dictionary argument named 'context'
    def __init__(self, *args, **kwargs)
        checkbox_context = kwargs.pop('context')
        super(SearchQuery,self).__init__(*args, **kwargs)
        #Now, instead of doing a bunch of if statements, we can say that
        # our dictionary passed a series of True and False keys that will
        # tell us how our checkboxes should be, in their initial state
        self.fields['checkbox_one'].initial = context['box1']
    checkbox_one = forms.BooleanField()

因此,假设我们通过了context = {'box1':True},那么我们的复选框将呈现为初始值"True"或"Checked"

最新更新