4

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:

Error:

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?

1
  • 3
    form_class = SignForm(...) is initializing the form, it should simply be defining which form to use. Try changing it to form_class = SignForm, as far as setting the initial values, look at this question: stackoverflow.com/questions/22083218/… Commented Feb 5, 2015 at 18:27

2 Answers 2

2

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

Docs are available here.

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

Comments

2

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'}

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.