0

models.py:

class Person(models.Model):
    GENDER_SELECT = (
        ('f', 'Female'),
        ('m', 'Male'),
        ('o', 'Other'),
    )
    TITLE_SELECT = (
        ('0', 'Mr.'),
        ('1', 'Mrs.'),
        ('2', 'Ms.'),
        ('3', 'Mast.'),
    )
    title=models.CharField(max_length=5,choices=TITLE_SELECT)
    name=models.CharField(max_length=100)
    gender=models.CharField(max_length=11,choices=GENDER_SELECT)

forms.py:

class PersonForm(ModelForm):
    class Meta:
        model=Person
        fields='__all__'
        widgets={
            'title': forms.RadioSelect(),
            'gender': forms.RadioSelect(),
        }

template:

<form action="" method="post">
        {% csrf_token %}
        {{form1.as_p}}
        <input type="submit" value="Submit">
    </form>

Output:

Person

As you can see, the fields display as verticals whereas I want them horizontal. Plus, I don't want that initial '__________' choice. How can I achieve it?

noob87
  • 41
  • 10

2 Answers2

0

To replace the dashed lines you can use the empty label attribute in your model choice field, so for example :

forms.ChoiceField(empty_label="(Select here)")

Or set it to None or empty string if you don't want anything

As for the horizontal render you can provide your own renderer so something like that would work :

from django.utils.safestring import mark_safe

class HorizontalRadioRenderer(forms.RadioSelect.renderer):
  def render(self):
    return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))

  forms.ChoiceField(choices=APPROVAL_CHOICES, empty_label="(Select here)",widget=forms.RadioSelect(renderer=HorizontalRadioRenderer))

or if you are using bootstrap :

forms.ChoiceField(choices=APPROVAL_CHOICES, empty_label="(Select here)", attrs={'class': 'form-check-inline'})
Gaëtan GR
  • 1,380
  • 1
  • 5
  • 21
0

To remove the empty label (the dashed lines) in a ModelForm, configure the underlying model field so that the default value is None:

class Person(models.Model):
    GENDER_SELECT = (
        ('f', 'Female'),
        ('m', 'Male'),
        ('o', 'Other'),
    )
    TITLE_SELECT = (
        ('0', 'Mr.'),
        ('1', 'Mrs.'),
        ('2', 'Ms.'),
        ('3', 'Mast.'),
    )
    title=models.CharField(max_length=5,choices=TITLE_SELECT, default=None)
    name=models.CharField(max_length=100)
    gender=models.CharField(max_length=11,choices=GENDER_SELECT, default=None)

Hat tip to https://stackoverflow.com/a/24868776/308204 (I had a hard time finding the answer too).

Mathieu Dhondt
  • 8,405
  • 5
  • 37
  • 58