Django-models:Choices,select,widget如何更改widget的默认选项

时间:2012-09-27 09:10:15

标签: django django-models django-templates

我有模型问题,例如我有

fallBack = models.CharField(max_length=100, choices=FALLBACK,  default = 99,blank = True,null = True)
FALLBACK = (
    (u'99','-'),
    (u'standard', u'Standard TPF deactivation/exlusion applies'),
    (u'fallback', u'Fallback script provided'),
    (u'na',u'N/A'),
    (u'other',u'Other'),
    )

如果我将在模板中使用

{% for obj in form.forms %}
    {{obj.fallBack}}
{% endfor %}

它会像这样返回sthing

<select name="form-0-fallBack" id="id_form-0-fallBack">
    <option value="">---------</option>
    <option value="99" selected="selected">-</option>
    <option value="standard">Standard TPF deactivation/exlusion applies</option>
    <option value="fallback">Fallback script provided</option>
    <option value="na">N/A</option>
    <option value="other">Other</option>
</select>

但我想做这样的事情:

<select **onchange="javascript:make()"** name="form-0-fallBack" id="id_form-0-fallBack">
    <option value="">---------</option>
    <option value="99" selected="selected">-</option>
    <option value="standard">Standard TPF deactivation/exlusion applies</option>
    <option value="fallback">Fallback script provided</option>
    <option value="na">N/A</option>
    <option value="other">Other</option>
</select>

怎么做? 我可以在模板中写这个secound选项而不是{{obj.fallBack}}但是然后我的formset.is_valid()不起作用,当我做这样的事情时:

1)I will choose from fallBack second option(Standard TPF deactivation/exlusion applies) 
2) submit,
3) I have some error in other place in template 
4) Then my obj.fallBack returning to default option (99 , -) 

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

查看Widgets

上的django文档
widget=forms.Select(attrs={'onchange': 'javascript:make()'})

这看起来像ModelForm,请查看如何为ModelForms指定小部件

答案 1 :(得分:0)

Ok所以使用此属性创建新的Field而不是charfield

widget=forms.Select(attrs={'onchange': 'javascript:make()'})

感谢您的帮助