めも
html
{{ form.title }}
djangoが以下のようなコードを自動出力している
<input type="text"
name="title"
id="id_title"
value="(前回の入力値など)"
class="... (フォームで設定したCSS)
">
<label for="{{ form.title.id_for_label }}">
id_for.labelでDjangoが生成した id="id_title" と一致
実際の出力イメージ テンプレ
<label for="{{ form.title.id_for_label }}">タイトル</label>
{{ form.title }}
出力結果
<label for="id_title">タイトル</label>
<input type="text" name="title" id="id_title">
from django import forms
from .models import Survey
# Django のフォームクラスを使用するために ModelForm を継承
class SurveyForm(forms.ModelForm):
# Metaクラスの中で、「どのモデルを使うか」「どのフィールドを操作するか」を定義
class Meta:
# このフォームが対応するモデルは Survey モデル
model = Survey
# フォームで入力/編集するフィールド
# モデルにあるフィールドのうち、これだけをフォームに表示する
fields = ["title", "description", "end_at", "is_public"]
# 各フィールドに対して使用するウィジェット(入力フォームの種類)を指定
widgets = {
# 「title」はテキスト入力欄にする
# attrs={} で HTML の属性を追加
# class="form-control" → Bootstrap用のCSS
"title": forms.TextInput(attrs={"class": "form-control"}),
}
#アンケート新規作成
class SurveyCreateView(CreateView):
model = Survey
form_class = SurveyForm # ← ModelForm を使う
template_name = "karakuchi_room/surveys_create.html"
success_url = None
def form_valid(self, form):
survey = form.save(commit=False)
user = self.request.user if self.request.user.is_authenticated else get_guest_user()
survey.user = user
survey.save()
messages.success(self.request, "アンケートを作成しました。")
return redirect("survey-list") # ← 成功時は必ず 302
def form_invalid(self, form):
logger.warning("SurveyCreate errors: %s", form.errors) # ← サーバーログに出す
return super().form_invalid(form)