user1050619 user1050619 - 1 year ago 224
Python Question

Select a valid choice..That choice is not one of the available choices

Here is my models and form in Django postgres database.When I try to create the mapspot object I get a error "Select a valid choice" even though its just a relational object.

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'))

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()
<Map: Map object>
>>> for each in Map.objects.all():
... print(,
1 Germantown
2 US
>>> spotform =MapSpotForm({'map':Map.objects.get(id=2),'position':'10,20'})
>>> spotform.is_valid()
>>> spotform.errors
{'map': ['Select a valid choice. That choice is not one of the available choices.']}

vd1 vd1
Answer Source

Default form field for ForeignKey is ModelChoiceField. ModelChoiceField "validates that given id exists in the queryset". Try next:

spotform = MapSpotForm({'map': Map.objects.get(id=2).id, 'position': '10,20'})