[Django] Give Form a dynamic initial value from Model

environment Python 3.5.0 Django 1.9.2

forms.py


class CakeForm(forms.Form):
    cake_num = IntegerField(label='Number of cakes', min_value=0)

    class Meta:
        model = Cake

views.py


def edit(request, store_id):
	#If you can get cake, set the initial value
	try:
		cake = Cake.objects.get(store=store_id)
		cake_form = CakeForm(initial = {
		    'cake_num': cake.cakenum    #initial value
		})
	#If cake cannot be obtained, the initial value is not set.
	except:
		cake_form = CakeForm()

References Put dynamic initial values in Django's Form--i2bs Diary

Recommended Posts

[Django] Give Form a dynamic initial value from Model
Get the value from the [Django] Form
[Django] Give an initial value to ChoiceField
Use django model from interpreter
Relationship between Bound / Unbound and initial value of Django2 Form
DJango Memo: From the beginning (model settings)
Create a model for your Django schedule
Get a reference model using Django Serializer
Use Django from a local Python script
DJango Note: From the beginning (form processing)
Implement a Custom User Model in Django
Get only the text from the Django form.
[Django] Create a form that automatically fills in the address from the zip code
DJango Memo: From the beginning (creating a view)
Run a Python file from html using Django