0

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?

2
  • 2
    You also can pass initial as parameter when you create your form form = CommentForm(initial={'storyId':xyz}) Commented Jun 6, 2012 at 10:38
  • thankyou, i did not know that and am grateful to find it out! Commented Jun 6, 2012 at 10:45

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Modelform is just a class so,you can access modelform variables straight away. There's no need for initial.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.