我有一个django项目,在项目中我有一个django forms.py,它包含一个字段调用类别,它选择由于对数据库进行查询而生成的框输入元素。 如果我从数据库的选择下拉列表中选择一个选项,我会一直收到错误:
**strong text**Select a valid choice. That choice is not one of the available choices
以下是代码:
Forms.py
from django import forms
#from django.contrib.auth.models import User
from signer.models import CreateSingleSigner
class CreateSingleSignerForm(forms.ModelForm):
category = forms.ModelChoiceField(
required = True,
help_text = 'category',
queryset=CreateSingleSigner.objects.all().values_list(
'category', flat=True
).distinct()
)
我的观点。
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from signer.models import CreateSingleSigner
from signer.forms import CreateSingleSignerForm
from django.template import RequestContext
def singlesigner(request):
context = {}
if request.method == 'POST':
createsinglesigner_form = CreateSingleSignerForm(data=request.POST)
if createsinglesigner_form.is_valid():
createsinglesigner.category = request.POST['category']
createsinglesigner_form.save()
else:
print createsinglesigner_form.errors
else:
# context['createsinglesigner'] = CreateSingleSigner()
createsinglesigner_form =CreateSingleSignerForm()
return render(request, "signer/singlesigner.html", {"createsinglesigner_form":createsinglesigner_form}, RequestContext(request))
my models.py
from django.db import models
class CreateSingleSigner(models.Model):
category = models.CharField(max_length = 32)
有人可以告诉我哪里出错了吗?
答案 0 :(得分:0)
尝试以下方法之一解决问题:
尝试在CreateSingleSigner
模型中定义unicode的转换:
class CreateSingleSignerForm(forms.Form):
def __unicode__(self):
return self. category
<强>说明强>:
ModelChoiceField
将使用指定字段的__unicode__
表示来显示和验证您的字段。
尝试在表单的__init__
方法中设置选项
class CreateSingleSignerForm(forms.Form):
category = forms.ChoiceField(choices=[], required=False)
def __init__(self, *args, **kwargs):
super(CreateSingleSignerForm, self).__init__(*args, **kwargs)
self.fields['category'].choices = CreateSingleSigner.objects.all().values_list('category', flat=True).distinct()
说明 ModelChoiceField
的查询集参数不能是values_list
,因为它会保存关系,所以django必须使用完整的模型对象,而不是模型对象的某些值。