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

后端 未结 5 1003
名媛妹妹
名媛妹妹 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:37

    Django <= 1.10

    RadioSelectNotNull widget

    from itertools import chain
    from django.forms import RadioSelect
    from django.utils.encoding import force_unicode
    
    class RadioSelectNotNull(RadioSelect):
    """
    A widget which removes the default '-----' option from 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 >= 1.11

    As after Django 1.10 following method is no more in RadioSelect or in its ancestors. That's why upper widget will not remove bogus choice generated by RadioSelect.

    def get_renderer(self, name, value, attrs=None, choices=()):
    

    So to remove bogus choice generated by RadioSelect use following widget. I have tested this till Django 2.0

    from django.forms import RadioSelect
    class RadioSelectNotNull(RadioSelect):
        """
        A widget which removes the default '-----' option from RadioSelect
        """
        def optgroups(self, name, value, attrs=None):
            """Return a list of optgroups for this widget."""
            if self.choices[0][0] == '':
                self.choices.pop(0)
            return super(RadioSelectNotNull, self).optgroups(name, value, attrs)
    

提交回复
热议问题