8
6

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 5 years have passed since last update.

[Django] ModelからFormに動的な初期値を与える

Last updated at Posted at 2016-02-21

環境
Python 3.5.0
Django 1.9.2

forms.py
class CakeForm(forms.Form):
    cake_num = IntegerField(label='ケーキの数', min_value=0)

    class Meta:
        model = Cake
views.py
def edit(request, store_id):
	# cake を取得できれば初期値を設定
	try:
		cake = Cake.objects.get(store=store_id)
		cake_form = CakeForm(initial = {
		    'cake_num': cake.cakenum    # 初期値
		})
	# cake を取得できなければ初期値を設定しない
	except:
		cake_form = CakeForm()

※ こういう時は普通 ModelForm 使うだろうけど。。。

参考文献
DjangoのFormに動的な初期値を入れる - i2bsの日記

8
6
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
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?