python - 如何摆脱 Django Form 的 RadioSelect 生成的虚假选择

标签 python django django-forms

我在 Django 1.3 上使用 ModelForm。

模型.py:

class UserProfile(models.Model):
...
gender = models.CharField(max_length=1, blank=True, choices=(('M', 'Male'), ('F', 'Female'), ('Unspecified', '')), default='M')
...

表单.py:

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = ('gender')
        widgets = {
            'gender': forms.RadioSelect(),
        }

当这个小部件呈现为 HTML 时,我得到了

<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> 

问题: 我怎样才能摆脱虚假的选择“--------”?

几个月前另一个 stackoverflow 用户提出了同样的问题 (Here)。我已经尝试了那里公认的解决方案(如您所见),但这对我不起作用。

最佳答案

即使没有 blank=True,它也会显示额外的输入。我创建了一个新的小部件:

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)

关于python - 如何摆脱 Django Form 的 RadioSelect 生成的虚假选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5824037/

相关文章:

python - 如何使用 python 在 google colab 中保存 json 转储?

django - 在代码中使用 django 内置过滤器(在模板之外)

python - 如何使用特定用户拥有的对象创建 ModelForm

Django:如何显示我自己的动态创建的字段

python - Pycharm Django Debugging 真的很慢

python - 如何设计我的 python 应用程序以跨多核并行工作

python - Sklearn imputer vs df.fillna 用列的平均值替换 nan 值

mysql - Django 的 unique_together 功能的性能成本是多少

python - Django:返回渲染可哈希错误

django - 自定义标签,例如使用 django-filter