OptimusPrime
OptimusPrime

Reputation: 859

Setting Initial Field in Django

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.

Upvotes: 0

Views: 28

Answers (1)

Exprator
Exprator

Reputation: 27503

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

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

Upvotes: 1

Related Questions