How to get rid of the bogus choice generated by RadioSelect of Django Form

后端 未结 5 1012
名媛妹妹
名媛妹妹 2021-01-02 03:48

I am using ModelForm on Django 1.3.

models.py:

class UserProfile(models.Model):
...
gender = models.CharField(max_length=1, blank=True, choices=((\'M         


        
5条回答
  •  爱一瞬间的悲伤
    2021-01-02 04:30

    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)
    

提交回复
热议问题