如何摆脱由RadioSelect Django Form生成的虚假选项 [英] How to get rid of the bogus choice generated by RadioSelect of Django Form

查看:113
本文介绍了如何摆脱由RadioSelect Django Form生成的虚假选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django 1.3上使用ModelForm。

I am using ModelForm on Django 1.3.

models.py:

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用户提出了同样的问题( Here )。我已经尝试了在那里接受的解决方案(你可以看到),但这对我来说并不奏效。

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.

推荐答案

即使没有空白= 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)

这篇关于如何摆脱由RadioSelect Django Form生成的虚假选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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