默认情况下,如何使用RadioSelect渲染Django表单而不检查单选按钮? [英] How to render a Django form with RadioSelect without getting a checked radiobutton by default?

查看:1323
本文介绍了默认情况下,如何使用RadioSelect渲染Django表单而不检查单选按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class myModelForm(ModelForm):在Django 1.2.1中,我使用ModelForm并生成一个带有单选按钮的表单: 
class Meta:
model = myModel
widgets = {
'choose':RadioSelect(),
}
/ pre>



这会产生一个额外的虚假值:

 < li>< input type =radioid =id_choose_0value =name =choose1/> ---------< /锂> 
< li>< input type =radioid =id_choose_1value =1name =choose1/>首选< / li>



我明白我可以摆脱自动生成的空输入字段通过设置默认值:

  myChoices =(
(1,First choice),( 2,第二选择),(3,第三选择),


class myModel(models.Model):
choose = models。 CharField(max_length = 1,choices = myChoices,default = 1 ...



所以在这种情况下,选择首选项:

 < li>< input checked =checkedtype =radioid =id_choose_1value =1name =choose1/>首选< / li> 
< li>< input type =radioid =id_choose_2 =2name =choose2/>第二选择< / li>



我的表单没有一个检查的输入属性?



(没有自动生成的)

解决方案

这是一个黑客的解决方案,但我e测试它工作:只需将字段的默认值设置为不是选项之一的值(我建议将其设置为)。当渲染表单时,Django将不知道哪个输入被标记为已检查,所以它将不会被检查(而不会引发错误)。而事实上,默认情况下将不会有自动生成的输入字段。


On Django 1.2.1 I'm using ModelForm and generating a form with radiobuttons:

class myModelForm(ModelForm):    
    class Meta:
        model = myModel
        widgets = {
            'choose': RadioSelect(),
        } 


This generates an extra input with bogus value:

<li><input type="radio" id="id_choose_0" value="" name="choose1" /> ---------</li>
<li><input type="radio" id="id_choose_1" value="1" name="choose1" /> First choice</li>


I understand that I can get rid of the auto-generated empty input field by setting a default:

myChoices = (
    ("1", "First choice"),("2", "Second choice"),("3", "Third choice"),
)    

class myModel(models.Model):
    choose = models.CharField(max_length=1, choices=myChoices, default=1...


So in this case the first choice is selected:

<li><input checked="checked" type="radio" id="id_choose_1" value="1" name="choose1" /> First choice</li>
<li><input type="radio" id="id_choose_2" value="2" name="choose2" /> Second choice</li>

But how do I render my form without a checked input attribute?

(and without the auto-generated one)

解决方案

This is kind of a hacky solution, but I've tested it to work: simply set the default for the field to a value that isn't one of the choices (I recommend setting it to None). When rendering the form, Django won't know which input to mark as checked, so it will leave all of them unchecked (without throwing an error). And the fact that there is a default means there will be no auto-generated input field.

这篇关于默认情况下,如何使用RadioSelect渲染Django表单而不检查单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆