💡

Djangoフォーム処理の備忘録

に公開

Djangoのフォームの色々

フォームクラスでの処理諸々

viewでフォームのChoiceFieldで動的な初期値を設定

クラスビューでget_context_dataでフォームのChoiceField(セレクトボックス)で選択肢を動的に行う

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['form'].fields['名称'].queryset = モデル名.objects.filter(条件)
    return context
def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['form'].fields['category'].queryset = Category.objects.filter(user=self.request.user.id)
    return context

get_context_dataが肥大化するという欠点もある

viewでフォームのCharFieldで初期値を設定

クラスビューでget_context_dataでフォームのCharaFieldなどに初期値を代入する

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context["form"].fields["名称"].initial = "代入する値"
    return context
def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context["form"].fields["name"].initial = "Bob"
    return context

get_context_dataが肥大化するという欠点もある

viewでフォームのChoiceFieldで動的な初期値を設定

クラスビューでget_formでフォームのChoiceField(セレクトボックス)で選択肢を動的に行う

def get_form(self):
    form = super().get_form()
    form.fields["名称"].queryset = モデル名.objects.filter(条件)
    return form
def get_form(self):
    form = super().get_form()
    form.fields["category"].queryset = Category.objects.filter(user=self.request.user.id)
    return form

だいぶ美しい

viewでフォームのCharFieldで初期値を設定

クラスビューでget_formでフォームのCharFieldなどに初期値を代入する

def get_form(self):
    form = super().get_form()
    form.fields["名称"].initial = "初期値となる値"
    return form
def get_form(self):
    form = super().get_form()
    form.fields["name"].initial = "Bob"
    return form

だいぶ美しい

Discussion