问题描述
我有一个外键相关的两个模型:
I have two models related by a foreign key:
# 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)
默认情况下,django ModelForm将呈现这作为< select>
与< option>
s;然而,我希望这个函数作为一个自由的表单输入,< input type =text/>
,并在幕后获取或创建必要的TestSource对象,然后将其与TestModel对象相关联。
By default, a django ModelForm will present this as a <select>
with <option>
s; however I would prefer that this function as a free form input, <input type="text"/>
, and behind the scenes get or create the necessary TestSource object and then relate it to the TestModel object.
我已经尝试定义一个自定义的ModelForm和Field来完成此操作:
I have tried to define a custom ModelForm and Field to accomplish this:
# 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'}),
}
不幸的是,得到: int()的无效字面值为10:'test3'
当尝试在提交表单上检查 is_valid
。我哪里错了?是否可以完成这项工作?
Unfortunately, I am getting: invalid literal for int() with base 10: 'test3'
when attempting to check is_valid
on the submitted form. Where am I going wrong? Is their and easier way to accomplish this?
推荐答案
这样做应该有效:
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')
这篇关于Django ModelForm上的ForeignKey Field的自由格式输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!