1.models.py
from django.db import models
class MyModel(models.Model):
OPTIONS = [
('option1', 'Option 1'),
('option2', 'Option 2'),
('option3', 'Option 3'),
]
radio_field = models.CharField(max_length=10, choices=OPTIONS)
2.forms.py
from django import forms
from .models import MyModel
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['radio_field']
widgets = {
'radio_field': forms.RadioSelect,
}
3.views.py
from django.views.generic import CreateView
from .forms import MyForm
from .models import MyModel
class MyCreateView(CreateView):
model = MyModel
form_class = MyForm
template_name = 'my_template.html'
success_url = '/success/'
4.テンプレートファイル(create)
<!-- my_template.html -->
<!DOCTYPE html>
<html>
<head>
<title>My Form</title>
</head>
<body>
<h1>ラジオボタンフォーム</h1>
<form method="post">
{% csrf_token %}
{{ form.radio_field.label_tag }}<br>
{{ form.radio_field }}<br>
<button type="submit">送信</button>
</form>
</body>
</html>
↑は手動で入力フォームのレイアウト作りたい時
自動で入力フォーム作る時は、
{{ form.radio_field.label_tag }}<br>
{{ form.radio_field }}<br>
↑この部分を↓にすればOK
{{ form.as_p }}



コメント