我有两个与外键相关的模型:
# 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提交的表格时.我哪里错了?是他们更容易实现这一目标的方法吗?