在我的 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/