我正在尝试使用自定义字段填充数据模型表单。但是,外键抛出错误:
选择有效的选择。这种选择不是可用的选择之一 选择。
我无法理解我做错了什么:
models.py:
from django.db import models
class Name(models.Model):
first_name = models.CharField(max_length=10)
class Surname(models.Model):
first_name_key = models.ForeignKey(Name)
last_name = models.CharField(max_length=10)
forms.py:
from django import forms
from population.models import Surname
class SurnameForm(forms.ModelForm):
age = forms.IntegerField()
class Meta(object):
model = Surname
fields = ['first_name_key', 'last_name', 'age']
这就是我尝试填充模型的方法:
>> from population.models import Name, Surname
>> from population.forms import SurnameForm
>> f_name = Name(first_name='George')
>> model_data = {'first_name_key': f_name, 'id': 1, 'last_name': 'Taras', 'age': 2}
>> form = SurnameForm(model_data)
>> form.is_valid()
False
>> form.errors
{'first_name_key': ['Select a valid choice. That choice is not one of the available choices.']}
最后,以下代码按预期工作:
>> from population.models import Name, Surname
>> from population.forms import SurnameForm
>> f_name = Name(first_name='George')
>> f_name.save()
>> model_data = {'first_name_key': f_name.pk, 'last_name': 'Taras', 'age': 2}
>> form = SurnameForm(model_data)
>> form.is_valid()
True
答案 0 :(得分:1)
您不必传递id关键字,这是可选的。而不是传递f_name传递它的主键为f_name.pk:
model_data = {'first_name_key': f_name.pk, 'last_name': 'Taras', 'age': 2}``
顺便说一下,这似乎是一个奇怪的实现。为什么要创建模型名称。好奇。