Django 1.10.5
First, form.py, which is the source of form There is also a way to use ModelForm, but this time we will create something that is completed in form.py
form.py
from django import forms
from django.contrib.admin import widgets
import os
CHOICE = {
('0','cute'),
('1','cool'),
('2','passion'),
}
form SampleForm(forms.Form):
select = forms.ChoiceField(label='attribute', widget=forms.RadioSelect, choices= CHOICE, initial=0)
You can specify the items selected by default by setting ʻinitial = index If
required = False` does not require selection, it is better to remove it.
This time I will simply write a view that passes only this form
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}
)
As it is Let's do it
sample.html
{{ form }}
Basically, this is all you need, but if there are multiple input items in one form, you can control them individually as follows.
sample.html
{{ form.select.label }}{{ form.select}}
attribute
<ul id="id_select">
<li>
<label for="id_select_0">
<input checked="checked" id="id_select_0" name="purpose" type="radio" value="0" />
cute
</label>
</li>
<li>
....
</ul>
As you can see in the Official Reference, you have more control over the markup generated by turning with for. can For example, if you do as follows
sample.html
{{ form.select.label }}
{% for radio in form.select %}
{{ radio.tag }}
<label>{{ radio.choice_label }}</label>
{% endfor %}
Produces something that is (and will be) manageable
attribute
<input checked="checked" id="id_select_0" name="select" type="radio" value="0" />
<label>cute</label>
<input id="id_select_1" name="select" type="radio" value="1" />
<label>cool</label>
...
sample.html
{{ form.select.label }}
{% for radio in form.select %}
{{ radio.tag }}
<label for="id_select_{{ radio.index }}">{{ radio.choice_label }}</label>
{% endfor %}
If you do this
attribute
<input checked="checked" id="id_select_0" name="select" type="radio" value="0" />
<label for="id_select_0">cute</label>
<input id="id_select_1" name="select" type="radio" value="1" />
<label for="id_select_1">cool</label>
...
Yes
Recommended Posts