django形式错误:“选择不是可用选择之一”

时间:2015-10-16 07:36:49

标签: python django

我有2个应用。

输入:包含下拉列表的表单:region。下拉列表值来自结果数据库(由用户上传)。填写表单时,用户需要从下拉列表中选择值。

结果:拥有数据库

现在我可以在输入表单中显示“input”应用程序数据库的下拉列表。 (如图所示)。 enter image description here

我现在面临的问题是在选择并提交后,出现如下错误:

错误显示为:选择有效选项。选项不是可用选项之一。然后我不明白为什么,因为我确实从下拉列表中选择了选项。

提前感谢您的帮助以确定问题所在。

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>    

1 个答案:

答案 0 :(得分:1)

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

我改变了

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

取代之前的

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

然后它的工作原理。但我不明白为什么,希望有人能解释一下。