Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django forms give: Select a valid choice. That choice is not one of the available choices

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))
like image 233
user1102171 Avatar asked Dec 16 '11 15:12

user1102171


People also ask

What is valid form Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

How many types of Django forms are there?

Django form fields define two types of functionality, a form field's HTML markup and its server-side validation facilities.

What are the forms in Django?

Django provides a Form class which is used to create HTML forms. It describes a form and how it works and appears. It is similar to the ModelForm class that creates a form by using the Model, but it does not require the Model.


2 Answers

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 a ModelChoiceField and providing it with a list of tuples, not just ids. For example:

class CommandSubmitForm(ModelForm):
    iquery = LiveDataFeed.objects.values_list('unit_id', flat=True).distinct()
    iquery_choices = [('', 'None')] + [(id, id) for id in iquery]
    unit_id = forms.ChoiceField(iquery_choices,
                                required=False, widget=forms.Select())

You could also leave it as a ModelChoiceField, and use LiveDataFeed.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 subclass ModelChoiceField to override the label_from_instance method. You can see an example in the docs here.

like image 75
Dan Breen Avatar answered Oct 28 '22 08:10

Dan Breen


Before you call form.is_valid(), do the following:

  1. unit_id = request.POST.get('unit_id')

  2. form.fields['unit_id'].choices = [(unit_id, unit_id)]

Now you can call form.is_valid() and your form will validate correctly.

like image 40
Twengg Rich Avatar answered Oct 28 '22 07:10

Twengg Rich