I am unable to catch the values from the unit_id
after the selection is done by the user and data is posted. Can someone help me to solve this.
The values of the unit_id
drop down list is obtained from another database table (LiveDataFeed
). And once a value is selected and form posted, it gives the error:
Select a valid choice. That choice is not one of the available choices.
Here is the implementation:
in models.py:
class CommandData(models.Model):
unit_id = models.CharField(max_length=50)
command = models.CharField(max_length=50)
communication_via = models.CharField(max_length=50)
datetime = models.DateTimeField()
status = models.CharField(max_length=50, choices=COMMAND_STATUS)
In views.py:
class CommandSubmitForm(ModelForm):
iquery = LiveDataFeed.objects.values_list('unit_id', flat=True).distinct()
unit_id = forms.ModelChoiceField(queryset=iquery, empty_label='None',
required=False, widget=forms.Select())
class Meta:
model = CommandData
fields = ('unit_id', 'command', 'communication_via')
def CommandSubmit(request):
if request.method == 'POST':
form = CommandSubmitForm(request.POST)
if form.is_valid():
form.save()
return HttpResponsRedirect('/')
else:
form = CommandSubmitForm()
return render_to_response('command_send.html', {'form': form},
context_instance=RequestContext(request))
You're getting a flat value_list back which will just be a list of the ids, but when you do that, you're probably better off using a plain
ChoiceField
instead of aModelChoiceField
and providing it with a list of tuples, not just ids. For example:You could also leave it as a
ModelChoiceField
, and useLiveDataFeed.objects.all()
as the queryset, but in order to display the id in the box as well as have it populate for the option values, you'd have to subclassModelChoiceField
to override thelabel_from_instance
method. You can see an example in the docs here.Before you call
form.is_valid()
, do the following:unit_id = request.POST.get('unit_id')
form.fields['unit_id'].choices = [(unit_id, unit_id)]
Now you can call
form.is_valid()
and your form will validate correctly.