【问题标题】:Django 3 - Align Radio Button HorizontallyDjango 3 - 水平对齐单选按钮
【发布时间】:2021-06-06 09:24:33
【问题描述】:

我在 Django3 中创建了用户注册表单。

在表单中,我希望为用户提供一个基于单选按钮的选择。

forms.py 看起来像

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

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

模型文件的样子。

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

我已经尝试了一些关于 SO 的答案中建议的 CSS 技巧,但没有运气。

我得到的结果是垂直对齐(杂乱)的单选按钮。

需要帮助。

【问题讨论】:

    标签: django django-models django-forms django-templates


    【解决方案1】:

    我在同样的问题上苦苦挣扎。我在这里找到了 JeremyG 的解决方案 Align radio buttons horizontally in django forms 为我工作,但它要求您使用引导程序。

    这是您的代码的外观。

       class SignUpForm(UserCreationForm):
       ....
           subscription_choice = (
            ('yearly', 'Yearly'),('monthly', 'Monthly'),
            )
    
        subscription_type  = forms.TypedChoiceField(
        choices = subscription_choice,
        widget = forms.RadioSelect(attrs={
            'class': 'form-check-inline'
        })
    

    或者,您可以将 CSS 中 ul 和 li 的样式更改为类似下面的样式,类似于 Maryam Tariq 在此处的回答 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;
    }
    

    键在哪里显示:inline-block;我发现其他属性有助于使它看起来像我想要的那样。

    【讨论】:

      猜你喜欢
      • 2012-08-31
      • 2014-07-27
      • 2011-08-21
      • 2014-03-17
      • 2017-03-09
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多