Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django form error :"the choice is not one of available choices"

Tags:

python

django

I have 2 apps.

input: has the form containing a drop down list: region. The drop down list values are coming from the database of result (uploaded by user). When filling the form, user needs to select the value from the drop down list.

result:have the database

Now I can show the drop down list from the database of "input" app in the input form. (shown in picture). enter image description here

The problem I face now is after selecting the choice and submit it, there is an error shown as below:

The error shows like: select a valid choice.The choice is not one of available choices. Then I don't see why because I indeed selected the choice from drop down list.

Thanks in advance for your help to pin point the problem.

models.py

from django import forms
from django.forms import ModelForm
from django.db import models
from dupont.models import Result
from datetime import date
from django.forms import widgets

class Input(models.Model):
    company=models.CharField(max_length=100)
    region=models.CharField(max_length=100)

    def __unicode__(self):
        return self.company

forms.py

from django import forms
from django.forms import ModelForm
from .models import Input
from dupont.models import Result
from django.contrib.auth.models import User,Group
from django.forms import widgets
from functools import partial
from django.forms.utils import ErrorList

class InputForm(forms.ModelForm):
    company=forms.CharField(widget=forms.TextInput, label="Company",error_messages={'required': 'Please enter the company name'},required=True)
    region = forms.ModelChoiceField(queryset=Dupont.objects.values('region').distinct(),widget=forms.Select(),empty_label="(Global)",to_field_name="supply_chain")
    error_css_class='error'
    required_css_class = 'required'

    class Meta:
        model = Input
        fields = ('company', 'region')

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render,render_to_response,get_object_or_404
from inputform.forms import InputForm
from inputform.models import Input
from dupont.models import Result
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.list import ListView
from django.contrib import messages
from django.template import RequestContext
from django.shortcuts import redirect

@csrf_exempt
def input(request):
    if request.method == 'POST':
        form = InputForm(request.POST)
        if form.is_valid():
            company = form.cleaned_data['company']
            region = form.cleaned_data['region']    /Is this one correct?
            form.save()
            return redirect('result')
        else:
            print form.errors

    else:
        form=InputForm()
    return render_to_response('inputform.html',{'form': form},context_instance=RequestContext(request))

html

<form method="post" action="{% url 'input' %}">
        {% csrf_token %}

        <!--company--> 
        <div class="field">
            {{ form.company.errors }}
            <label for="{{ form.company.id_for_label }}">Company:</label>
            {{ form.company }}
        </div>

        <!--Region-->
        <div class="field" >
            <label> Select the Region:
            {{ form.region }}
                {% for region in form.region.choices %}
                     <option value="region" name= "region" id="id_region">{{region}} </option>
                {% endfor %}
            </label>
        </div>

        <!--submit-->
        <div class="fieldWrapper">
        <p><input type="submit" value="Submit" /></p></div>

 </form>    
like image 399
Héléna Avatar asked Oct 31 '22 17:10

Héléna


1 Answers

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

I changed in

iquery = Result.objects.values_list('region', flat=True).distinct()
iquery_choices = [('', 'None')] + [(region,region) for region in iquery]
region = forms.ChoiceField(iquery_choices,required=False, widget=forms.Select())

replacing the previous

region=forms.ModelChoiceField(queryset=Dupont.objects.values('region').distinct(),widget=forms.Select())"

and then it works. But I don't understand why, hope someone could explain.

like image 125
Héléna Avatar answered Nov 15 '22 05:11

Héléna