我正在尝试使用两个下拉菜单创建一个网站:部门和课程编号。下拉菜单的数据来自我的SQL数据库的“courses”表。现在我的网站正确初始化并在下拉菜单中显示正确的选项。但是,当用户在下拉菜单中选择一个选项并提交他们的选择时,Django会抛出“选择一个有效的选择。该选择不是可用的选择之一。”错误。我怀疑我的表单的输出格式不正确,所以在我的数据库中找不到选择,但是我已经阅读了许多其他SO问题,并且仍然无处可去。任何帮助表示赞赏。
models.py
from django.db import models
class Dept(models.Model):
dept = models.CharField(max_length=255, db_column = 'dept')
class Meta:
managed = False
db_table = 'courses'
def __str__(self):
return self.dept
class Course_num(models.Model):
course_num = models.CharField(max_length=255, db_column = 'course_number')
class Meta:
managed = False
db_table = 'courses'
def __str__(self):
return self.course_num
forms.py
from django import forms
from .models import *
class CourseForm(forms.Form):
dept = forms.ModelChoiceField(
queryset=Dept.objects.values_list('dept', flat = True).distinct().\
order_by('dept').exclude(dept__isnull=True),
required=False,
empty_label="No preference",
label=u"Department")
course_num = forms.ModelChoiceField(
queryset=Course_num.objects.all().\
order_by('course_num').values_list('course_num', flat = True).\
distinct().exclude(course_num__isnull=True),
required=False,
empty_label="No preference",
label=u"Course Number")
views.py
def home(request):
context = {}
res = None
form_CourseForm = CourseForm()
if request.method == 'GET':
form_CourseForm = CourseForm(request.GET)
args = {}
if form_CourseForm.is_valid():
dept = form_CourseForm.cleaned_data['dept']
if dept:
args['dept'] = dept
course_num = form_CourseForm.cleaned_data['course_num']
if course_num:
args['course_num'] = course_num
...
答案 0 :(得分:1)
更改您的查询集并尝试
class CourseForm(forms.Form):
dept = forms.ModelChoiceField(
queryset=Dept.objects.distinct().
order_by('dept').exclude(dept__isnull=True),
required=False,
empty_label="No preference",
label=u"Department")
course_num = forms.ModelChoiceField(
queryset=Course_num.objects.distinct().
order_by('course_num').exclude(course_num__isnull=True),
required=False,
empty_label="No preference",
label=u"Course Number")