迷ったらコレ!Djangoフォームでラジオボタンを1つだけ選択するベストプラクティス

2024-04-02

Djangoフォームでラジオボタングループから1つだけ選択できるようにするには、いくつかの方法があります。

方法1:choice_attributesを使う

各ラジオボタンにchoice_attributes属性を設定することで、個別に属性を指定できます。

from django import forms

class MyForm(forms.Form):
    gender = forms.ChoiceField(
        choices=(
            ('male', '男性'),
            ('female', '女性'),
        ),
        widget=forms.RadioSelect(),
        choice_attributes={
            'male': {'checked': True},
        },
    )

上記の例では、male ラジオボタンがデフォルトで選択されます。

方法2:initialを使う

initial属性で初期値を設定することで、デフォルトで選択されるラジオボタンを指定できます。

from django import forms

class MyForm(forms.Form):
    gender = forms.ChoiceField(
        choices=(
            ('male', '男性'),
            ('female', '女性'),
        ),
        widget=forms.RadioSelect(),
        initial='male',
    )

方法3:JavaScriptを使う

JavaScriptを使って、ラジオボタングループから1つだけ選択できるようにすることもできます。

{% for choice in form.gender.choices %}
<input type="radio" name="gender" value="{{ choice.0 }}" id="{{ choice.0 }}">
<label for="{{ choice.0 }}">{{ choice.1 }}</label>
{% endfor %}

<script>
function onlyOneRadioButtonChecked() {
  const radioButtons = document.querySelectorAll('input[name="gender"]');
  for (const radioButton of radioButtons) {
    radioButton.addEventListener('change', (event) => {
      if (event.target.checked) {
        for (const otherRadioButton of radioButtons) {
          if (otherRadioButton !== event.target) {
            otherRadioButton.checked = false;
          }
        }
      }
    });
  }
}

onlyOneRadioButtonChecked();
</script>



from django import forms

class MyForm(forms.Form):
    gender = forms.ChoiceField(
        choices=(
            ('male', '男性'),
            ('female', '女性'),
        ),
        widget=forms.RadioSelect(),
        # 方法1:`choice_attributes`を使う
        # choice_attributes={
        #     'male': {'checked': True},
        # },
        # 方法2:`initial`を使う
        initial='male',
    )

# 方法3:JavaScriptを使う
# テンプレートファイル

# {% for choice in form.gender.choices %}
# <input type="radio" name="gender" value="{{ choice.0 }}" id="{{ choice.0 }}">
# <label for="{{ choice.0 }}">{{ choice.1 }}</label>
# {% endfor %}

# <script>
# function onlyOneRadioButtonChecked() {
#   const radioButtons = document.querySelectorAll('input[name="gender"]');
#   for (const radioButton of radioButtons) {
#     radioButton.addEventListener('change', (event) => {
#       if (event.target.checked) {
#         for (const otherRadioButton of radioButtons) {
#           if (otherRadioButton !== event.target) {
#             otherRadioButton.checked = false;
#           }
#         }
#       }
#     });
#   }
# }

# onlyOneRadioButtonChecked();
# </script>

上記コードを参考に、ご自身のプロジェクトに合わせてラジオボタンを実装してください。

補足

  • 上記コードはあくまでサンプルです。必要に応じて修正してください。
  • choice_attributesinitial、JavaScriptのいずれの方法を使用しても、ラジオボタングループから1つだけ選択することができます。
  • どの方法を使用するかは、プロジェクトの要件や開発者の好みによって異なります。



Djangoフォームでラジオボタンを1つだけ選択する他の方法

方法4:ModelFormを使う

ModelFormを使うと、モデルのフィールドに基づいてフォームを自動的に生成することができます。

from django import forms
from .models import MyModel

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ('gender',)

上記の例では、MyModelモデルのgenderフィールドに基づいてラジオボタンフィールドが自動的に生成されます。

方法5:カスタムウィジェットを使う

カスタムウィジェットを作成することで、ラジオボタンの挙動を独自にカスタマイズすることができます。

from django.forms import widgets

class OnlyOneRadioButtonWidget(widgets.RadioSelect):
    def render(self, name, value, attrs=None, choices=()):
        rendered = super().render(name, value, attrs, choices)
        rendered = rendered.replace('type="radio"', 'type="radio" onclick="onlyOneRadioButtonChecked(this)"')
        return rendered

上記の例では、OnlyOneRadioButtonWidgetというカスタムウィジェットを作成して、ラジオボタンが選択されたときにJavaScript関数を呼び出すようにしています。

方法6:RadioFieldを使う

RadioFieldを使うと、個別にラジオボタンフィールドを作成することができます。

from django import forms

class MyForm(forms.Form):
    gender_male = forms.RadioField(
        label='男性',
        value='male',
    )
    gender_female = forms.RadioField(
        label='女性',
        value='female',
    )

上記の例では、gender_malegender_femaleという2つのラジオボタンフィールドを作成しています。


html django forms


HTMLとCSSを使ってdiv内のspan要素を垂直方向に中央揃えする方法

text-align: center;を使うこれは最も簡単な方法で、インライン要素である<span>要素に対してのみ有効です。親div要素にtext-align: center;プロパティを設定することで、その中のすべてのインライン要素が垂直方向に中央揃えになります。...