Reputation: 16214
i have a modelform like so:
class CommentForm(forms.ModelForm):
storyId = forms.IntegerField(required=True, widget=forms.HiddenInput())
postId = forms.IntegerField(required=True, widget=forms.HiddenInput())
so now i want to change the value of the "storyId"
i've found that, in my code i need to do this:
form = CommentForm()
form.initial['storyId'] = xyz
or in the init of the model i need this:
self.initial['storyId'] = xyz
what is the "initial" doing? Why cannot i just go straight to:
form = CommentForm()
form.storyId = xyz
thanks!
UPDATE if i run form.storyId = xyz
, then in the template, I will not see the value passed in. If i run
form.initial['storyId'] = xyz
then in the template i do see the values passed in! No other code changes, any ideas?
Upvotes: 0
Views: 167
Reputation: 1791
The parameter "initial" is used in forms.Form class generally to initialize a value that you would like to see as auto-filled, when the form is rendered.
In case of ModelForm, initial is used when you need to autofill a field that's called from the forms's init method.
form = CommentForm()
form.storyId = xyz
In the above code you are assigning directly the value to a property of a Python Instance, then the type of the property also changes.
The variable storyId is actually a django.forms.fields.IntegerField, and this has a parameter "initial" that would initialize the value.
Once you assign form.storyId=xyz, then storyId, takes the value of xyz, and will not be rendered as a form field.
I hope this is clear.
Upvotes: 1
Reputation: 5550
Modelform is just a class so,you can access modelform variables straight away. There's no need for initial.
Upvotes: 1