html - 如何自定义 Django 模板中单选按钮的显示?

标签 html django radio-button

在我的 forms.py 中,我有这个,其中 supbplansTuple 是元组的元组:

class RegisterForm(UserCreationForm):
    subChoices= forms.ChoiceField(label=_("Choose plan"), widget=forms.RadioSelect, choices=subPlansTuple)

subplansTuple 看起来像这样:

(("plan_1234","$5 a month"),("plan_2345","$10 a month"))

register.html 有这个:

<form id="register-form" name="regForm" method="post">
    {% csrf_token %}
    {% for field in registration_form %}
        <p>{{ field }}</p>  
    {% endfor %}
</form>

问题是,Django 像这样显示单选按钮小部件:

<p></p>
<ul id="id_subChoices">
  <li>
    <label for="id_subChoices_0"><input id="id_subChoices_0" name="subChoices" type="radio" value="plan_1234" required=""> $5 a month</label>
  </li>
  <li>
    <label for="id_subChoices_1"><input id="id_subChoices_1" name="subChoices" type="radio" value="plan_2345" required=""> $10 a month</label>
  </li>
</ul>
<p></p>

我不希望单选按钮以这种方式显示。如何自定义 HTML,也许看起来像 Boostrap's inline radio buttons .

最佳答案

您的字段对象具有允许您单独呈现输入的属性,因此在模板中您可以使用 {{field.tag}} ,它仅呈现字段标记和顶部您可以放置​​一个标签,并在 label 属性内放置输入 id {{field.id_for_label}}。这样:

<form action="" method="post">
    {% csrf_token %}
    {% for field in registration_form %}
        <label for="{{field.id_for_label}}">{{field.choice_label}}</label>
        {{field.tag}}
    {% endfor %}
</form>

然后我们可以通过类使用css进行自定义,使用浏览器在源代码中查看它们的类,或者通过RadioButton<的attrs属性在forms类中定义类 类并在 css 库中使用它,这一切都由您自行决定。 https://docs.djangoproject.com/en/3.1/ref/forms/widgets/#radioselect

关于html - 如何自定义 Django 模板中单选按钮的显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48937939/

相关文章:

html - 降低使用 recorderjs 创建的 WAV 文件的比特率

javascript - 使用 :class 应用类

python - 使用 Mock 修补 render_to_response

android - fragment 中的单选按钮 findViewById

javascript - 如何从 HTML 获取样式属性的第一个属性?

javascript d3 可视化在单击 HTML 输入之前不会加载/显示

django 最后 30 个条目列表及计数

Django is_staff 权限装饰器

jsp - 如何根据从数据库检索的值检查单选按钮?

JQuery 和 ASP :RadioButton and . 更改() 不起作用