Django ModelForm上的ForeignKey Field的自由格式输入

编程入门 行业动态 更新时间:2024-10-07 20:35:49
本文介绍了Django ModelForm上的ForeignKey Field的自由格式输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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的自由格式输入

本文发布于:2023-11-28 08:14:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641625.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:格式   自由   ModelForm   Django   Field

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!