Reputation: 287
I'm using Django django.forms.Form
and django.views.generic.edit.FormView
to render a HTML template.
I would to add a default value for some of the fields in my form but it encounters a problem:
Here is my code:
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView
class SignForm(forms.Form):
greeting_message = forms.CharField(
label='Greeting message',
widget=forms.Textarea,
required=True,
max_length=100,
)
book_name = forms.CharField(
label='Guestbook name',
max_length=10,
required=True,
)
class SignView(FormView):
"""Assign initial value for field 'book_name'."""
form_class = SignForm(
initial={
'book_name': 'aaaa'
}
)
def form_valid(self, form):
...
Can anyone help me?
Upvotes: 4
Views: 869
Reputation: 13178
Like the comment above says, you must assign form_class
just to the class. By doing what you have with the parenthesis and arguments, you are instantiating an object, which is why you have an exception.
Instead, to set initial data, define the get_initial
function, like so:
def get_initial(self):
initial = super(SignView, self).get_initial()
initial['book_name'] = 'aaaa'
return initial
Upvotes: 2
Reputation: 77241
You are attributing an instance to form_class
instead of a form class like the name of the attribute implies. SignForm
is the class, SignForm(*args)
is an instance.
You should override the get_initial()
method in the view:
def get_initial():
return {'book_name': 'aaaa'}
Upvotes: 2