0

I have a model form and I am trying to pass an initial value to one of the fields when I call the form from the view.

My view has the following:

threadform = ThreadForm(text="hello")

The model form is as below:

class ThreadForm(ModelForm):

class Meta:
    model = Thread
    fields = ['title']

def __init__ (self,*args, **kwargs):
    self.fields['title'].initial = kwargs.pop("text")
    super (ThreadForm, self).__init__(*args, **kwargs)

This will give the error "ThreadForm" has no attribute 'fields'.

If I reverse the super call then get "init() got an unexpected keyword argument 'text'".

Please can someone help as I can't find any information on the correct way to do this as others seem to be setting a hard coded initial value, but mine is dynamic as I want to replace the literal "hello" with data from a model.

2
  • You've probably solved this by now but it looks to me as if you should just switch the last two lines. Inherit from super before you try to set the initial value of title based on kwargs Commented Apr 23, 2020 at 9:09
  • Thanks, I think that's it. I asked this over a year ago and have since massively improved my Django and Python skills. What you're saying makes sense. I've recently made some Django apps and am much better with their forms now. Thanks for answering anyway :-) Commented Apr 24, 2020 at 13:13

1 Answer 1

1
threadform = ThreadForm(initial={'fieldname': value})

you can just do this, without the constructor in the form

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

1 Comment

I will try that, but I think I had already tried that and it didn't work, but initially I was binding the form to the request. I will let you know if it works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.