Django ModelForm上的ForeignKey字段的自由格式输入

bro*_*145 11 django django-models django-forms

我有两个与外键相关的模型:

# models.py    
class TestSource(models.Model):
  name        = models.CharField(max_length=100)

class TestModel(models.Model):
  name        = models.CharField(max_length=100)
  attribution = models.ForeignKey(TestSource, null=True)
Run Code Online (Sandbox Code Playgroud)

默认情况下,django ModelForm会将其显示为<select>with <option>; 但我更喜欢这个函数作为自由格式输入,<input type="text"/>并在幕后获取或创建必要的TestSource对象,然后将其与TestModel对象相关联.

我试图定义一个自定义ModelForm和Field来完成这个:

# forms.py
class TestField(forms.TextInput):
  def to_python(self, value):
    return TestSource.objects.get_or_create(name=value)

class TestForm(ModelForm):
  class Meta:
    model=TestModel
    widgets = {
      'attribution' : TestField(attrs={'maxlength':'100'}),
    }
Run Code Online (Sandbox Code Playgroud)

不幸的是,我得到了:invalid literal for int() with base 10: 'test3'当试图检查is_valid提交的表格时.我哪里错了?是他们更容易实现这一目标的方法吗?

Sam*_*lan 11

这样的事情应该有效:

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')
Run Code Online (Sandbox Code Playgroud)