0

I have created user signup form in Django3.

In the form I want to have a radio button based choice selection for the user.

The forms.py looks like

   class SignUpForm(UserCreationForm):
   ....
       subscription_choice = (
        ('yearly', 'Yearly'),('monthly', 'Monthly'),
        )

    subscription_type  = forms.TypedChoiceField(
    choices = subscription_choice,
    widget = forms.RadioSelect(attrs={
        "style": "display: inline-block"
    })

The model file looks like.

class SignUp(AbstractBaseUser):

    subscription_choice = (
        ('yearly', 'Yearly'),('monthly', 'Monthly'),
        )

    email = models.EmailField(unique=True)
    firstname = models.CharField(max_length=150)
    lastname = models.CharField(max_length=150)
    phonenumber = models.CharField(max_length=14,primary_key=True)
    referral_code = models.CharField(max_length=150, default="None")
    subscription_type = models.CharField(max_length=10, default="monthly", choices=subscription_choice)
    ....
    

I have tried some css tricks as suggested in some answers on SO but no luck.

The result I am getting is vertical aligned (messy) radio buttons.

enter image description here

Need some help.

Puneet7nov
  • 32
  • 6

1 Answers1

1

I was struggling with the same issue. I found the solution from JeremyG here Align radio buttons horizontally in django forms worked for me but it requires you to be using bootstrap.

Here is how your code would look.

   class SignUpForm(UserCreationForm):
   ....
       subscription_choice = (
        ('yearly', 'Yearly'),('monthly', 'Monthly'),
        )

    subscription_type  = forms.TypedChoiceField(
    choices = subscription_choice,
    widget = forms.RadioSelect(attrs={
        'class': 'form-check-inline'
    })

Alternatively, you can change the style of ul and li in your CSS to something like below in a similar way to Maryam Tariq's answer here Align radio buttons horizontally in django forms

ul {
    width: 100%;
    margin: 0;
    padding: 0;
}
li {
    list-style-type: none;
    display: inline-block;
    padding-right: 10%;
    width: auto;
    margin-right: 0.5%;
    padding-left: 0;
    margin-left: 0;
    margin: 1em 0;
}

where the key is display: inline-block; I found the other properties useful to make it look how I wanted it.