LoginSignup
17
11

More than 5 years have passed since last update.

【Django】ラジオボタンを設置したり、マークアップを整形したりする

Last updated at Posted at 2017-02-24

環境

Django 1.10.5


form.pyを作る

まずはformの元となるform.pyを
ModelFormを利用する方法もありますが、今回はform.pyの中で完結するものをつくっていきます

form.py
from django import forms
from django.contrib.admin import widgets
import os

CHOICE = {
    ('0','キュート'),
    ('1','クール'),
    ('2','パッション'),
}

form SampleForm(forms.Form):
    select = forms.ChoiceField(label='属性', widget=forms.RadioSelect, choices= CHOICE, initial=0)

initial = indexとすることでデフォルトで選択されている項目を指定できます
仮にrequired = Falseで選択を必須としない場合は、外しておいたほうが良いでしょう

views.pyを作る

今回は単純にこのフォームだけを渡すビューを書いていきます

views.py
from django.shortcuts import render, get_object_or_404, redirect
from forms.forms import *

def sample_view(request):
    form = SampleForm
    return render(request,
        project/sample.html,
        {"form" : form}
    )


html側でformを呼び出す

そのままです
やっていきましょう

sample.html
{{ form }}

基本的にこれだけでもいいですが一つのフォームの中で複数の入力項目がある場合、以下のように個別にコントロールしてもよいです

sample.html
{{ form.select.label }}{{ form.select}}



上記で簡単にラジオボタンを設置することができますが、難点は生成されるマークアップは<ul>で囲まれてしまっているので、やや扱いづらいものとなっている点です
こんな感じで

属性
<ul id="id_select">
    <li>
        <label for="id_select_0">
            <input checked="checked" id="id_select_0" name="purpose" type="radio" value="0" />
            キュート
        </label>
    </li>
    <li>
        ....
</ul>


生成されるマークアップを細かくコントロールする

こちらについては公式リファレンスでも書かれている通り、forで回すことで生成されるマークアップをより細かくコントロールすることができます
例えば以下のようにやってあげると

sample.html
{{ form.select.label }}
{% for radio in form.select %}
    {{ radio.tag }}
    <label>{{ radio.choice_label }}</label>
{% endfor %}

扱いやすい(であろう)ものが生成されます

属性
<input checked="checked" id="id_select_0" name="select" type="radio" value="0" />
<label>キュート</label>
<input id="id_select_1" name="select" type="radio" value="1" />
<label>クール</label>         
...



また、例えばlabelタグにラジオボタン側のidを与えたい場合などは

sample.html
{{ form.select.label }}
{% for radio in form.select %}
    {{ radio.tag }}
    <label for="id_select_{{ radio.index }}">{{ radio.choice_label }}</label>
{% endfor %}

このようにすると

属性
<input checked="checked" id="id_select_0" name="select" type="radio" value="0" />
<label for="id_select_0">キュート</label>
<input id="id_select_1" name="select" type="radio" value="1" />
<label for="id_select_1">クール</label>         
...

はい

17
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
11