Free-form input for ForeignKey Field on a Django ModelForm
There are a few problems here.
Firstly, you have defined a field, not a widget, so you can't use it in the widgets
dictionary. You'll need to override the field declaration at the top level of the form.
Secondly get_or_create
returns two values: the object retrieved or created, and a boolean to show whether or not it was created. You really just want to return the first of those values from your to_python
method.
I'm not sure if either of those caused your actual error though. You need to post the actual traceback for us to be sure.
Something like this should work:
class TestForm(ModelForm):
attribution = forms.CharField(max_length=100)
def save(self, commit=True):
attribution_name = self.cleaned_data['attribution']
attribution = TestSource.objects.get_or_create(name=attribution_name)[0] # returns (instance, <created?-boolean>)
self.instance.attribution = attribution
return super(TestForm, self).save(commit)
class Meta:
model=TestModel
exclude = ('attribution')