如何摆脱 Django Form 的 RadioSelect 生成的虚假选择 [英] How to get rid of the bogus choice generated by RadioSelect of Django Form
本文介绍了如何摆脱 Django Form 的 RadioSelect 生成的虚假选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Django 1.3 上使用 ModelForm.
I am using ModelForm on Django 1.3.
models.py:
class UserProfile(models.Model):
...
gender = models.CharField(max_length=1, blank=True, choices=(('M', 'Male'), ('F', 'Female'), ('Unspecified', '')), default='M')
...
forms.py:
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = ('gender')
widgets = {
'gender': forms.RadioSelect(),
}
当这个小部件被渲染成 HTML 时,我得到了
When this widget is rendered into HTML, I got
<ul>
<li><label for="id_gender_0"><input type="radio" id="id_gender_0" value="" name="gender" />---------</label></li>
<li><label for="id_gender_1"><input checked="checked" type="radio" id="id_gender_1" value="M" name="gender" /> Male</label></li>
<li><label for="id_gender_2"><input type="radio" id="id_gender_2" value="F" name="gender" />Female</label></li>
<li><label for="id_gender_3"><input type="radio" id="id_gender_3" value="" name="gender" /> Unspecified</label></li>
</ul>
问题:我怎样才能摆脱虚假的选择--------"?
Problem: How can I get rid of the bogus choice "--------"?
几个月前另一个 stackoverflow 用户提出了同样的问题(此处).我已经在那里尝试了公认的解决方案(如您所见),但这对我不起作用.
The same problem was brought up by another stackoverflow user months ago (Here). I have tried the accepted solution in there (as you can see) but that didn't work for me.
推荐答案
即使没有 blank=True 它也会显示额外的输入.我创建了一个新的小部件:
Even without blank=True it shows the extra input. I have created a new Widget:
from itertools import chain
from django.forms import RadioSelect
from django.utils.encoding import force_unicode
class RadioSelectNotNull(RadioSelect):
def get_renderer(self, name, value, attrs=None, choices=()):
"""Returns an instance of the renderer."""
if value is None: value = ''
str_value = force_unicode(value) # Normalize to string.
final_attrs = self.build_attrs(attrs)
choices = list(chain(self.choices, choices))
if choices[0][0] == '':
choices.pop(0)
return self.renderer(name, str_value, final_attrs, choices)
这篇关于如何摆脱 Django Form 的 RadioSelect 生成的虚假选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文