0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Djangoのforms.ModelFormでフォームの初期値を設定する

Last updated at Posted at 2021-01-28

環境

  • Django 3.0.3

init関数で初期値を設定

fieldsで登録したfieldに対してdef __init__()内で初期値を入れます。

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ('title', 'price' )

    # フィールドを初期化
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(ProductForm, self).__init__(*args, **kwargs)
        self.fields['price'].initial = 1000

テンプレートビューを使っていてもforms.ModelFormで初期値を設定すれば、フォームに初期値を入れることができます。

from django.views import generic
from apps.products.forms import ProductForm


class ProductCreateView(generic.CreateView):
    """ 新規登録 """
    model = Product
    form_class = ProductForm
    template_name = "products/add.html"
    raise_exception = True # 403ページの表示


class ProductUpdateView(generic.UpdateView):
    """ 更新 """
    model = Product
    form_class = ProductForm
    template_name = 'products/edit.html'
    raise_exception = True
    pk_url_kwarg = "id"
    success_url = reverse_lazy('products:index')

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?