这是我在Django postgres数据库中的模型和表单。当我尝试创建mapspot对象时,我得到一个错误"选择一个有效的选择"即使它只是一个关系对象。
models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.postgres.fields import ArrayField
class Map(models.Model):
name = models.CharField(max_length=128)
class MapSpot(models.Model):
map = models.ForeignKey('polls.Map', related_name='polls')
position = ArrayField(models.IntegerField(), size=2)
position1 = models.IntegerField(default=0)
class Meta:
unique_together = (('map', 'position'))
forms.py
from django.forms import ModelForm
from .models import Map, MapSpot
class MapForm(ModelForm):
class Meta:
model = Map
fields = ['name']
class MapSpotForm(ModelForm):
class Meta:
model = MapSpot
fields = ['map','position']
>>> form = MapForm({'name':'US'})
>>> form.is_valid()
True
>>> form.save()
<Map: Map object>
>>> for each in Map.objects.all():
... print(each.id, each.name)
...
1 Germantown
2 US
>>> spotform =MapSpotForm({'map':Map.objects.get(id=2),'position':'10,20'})
>>> spotform.is_valid()
False
>>> spotform.errors
{'map': ['Select a valid choice. That choice is not one of the available choices.']}
答案 0 :(得分:3)
ForeignKey
的默认表单字段为ModelChoiceField
。 ModelChoiceField
&#34;验证查询集中存在给定ID&#34;。尝试下一步:
spotform = MapSpotForm({'map': Map.objects.get(id=2).id, 'position': '10,20'})