2014-09-03 76 views
0

我有一个ModelForm,我使用django-widget-tweaks在模板中呈现。我有一个ChoiceField选择打印出这样的事情:Django:如何添加动态类来选择表单中的选项

<select> 
    <option value="object.id">object.name</option> 
</select> 

但对于JavaScript操作的目的,我必须满足下列条件:

<select> 
    <option value="object.id" class="object.otherPropery">object.name</option> 
</select> 

django-widget-tweaks has an add_class function,但它只是增加了一个类来选择框,不是包含的选项。

我也曾尝试我自己的滚动选择框:

<select> 
    {% for object in form.object_field %} 
     <option value="{{ object.id }}" class="{{ object.otherProperty }}">{{ object.name }}</option> 
    {% endfor %} 
</select> 

但是,当表格没有验证,并返回错误,用户之前选择的选项被重置回默认(第一个)选项(这个确实发生在django-widget-tweaks中)。

我也尝试覆盖Select小部件的render_optionrender_options字段,但该对象的附加属性未传递给这些函数。

我觉得有一个简单的解决方案,我想要做什么。任何帮助将非常感激!

回答

2

我想你可以做这样的事情(注意是“如果”标签):

<select> 
    {% with value=form.object_field.value %} 
     {% for object in form.object_field %} 
      <option 
       value="{{ object.id }}" 
       class="{{ object.otherProperty }}" 
       {% if object.id == value %}selected="selected"{% endif %} 
      > 
       {{ object.name }} 
      </option> 
     {% endfor %} 
    {% endwith %} 
</select> 

虽然如果条件可能无法在真正的结果,当它应该,如果object.id是一个整数,因为导致value将始终是已提交表单的字符串(POST/GET查询数据中的所有值均为字符串)。但是,如果值来自'initial_data',它将是整数。

对于这样的情况下,您可以按以下步骤更新你的 '如果' 标签:

{% if object.id|slugify == value|slugiy %}selected="selected"{% endif %} 

做最后的代码如下:

<select> 
    {% with value=form.object_field.value %} 
     {% for object in form.object_field %} 
      <option 
       value="{{ object.id }}" 
       class="{{ object.otherProperty }}" 
       {% if object.id|slugify == value|slugify %}selected="selected"{% endif %} 
      > 
       {{ object.name }} 
      </option> 
     {% endfor %} 
    {% endwith %} 
</select> 
+0

完美。谢谢Debanshu! – 2014-09-05 17:41:06

0

我认为在向选项元素添加类或其他任何东西时存在问题。我知道适用于某些CSS,看到这个其他职位,例如:Can we add class attribute in option element? 我认为相同的可能适用于操纵它与JavaScript。

这可能有点棘手,但也可以在模板中写出一些将{{object.id}}映射到{{object.otherProperty}}的JavaScript,以便您可以访问办法。

相关问题