在django中,我怎样才能创建一个可选的formField来每次访问db时访问db?
现在行:
status = forms.ChoiceField(choices=FormsTools.StatusesToTuples(Status.objects.all()))
加载django时执行,而不是每次显示表单时执行。
如何让场地动态化?因此,每次显示表单时,可选字段都将具有db?
更新: POST数据:
.
status: u'4'
.
.
在模型中,该字段如下所示:status = models.IntegerField()
观点:
def edit_call(request, call_id):
c = Call.objects.get(id=call_id)
if request.POST:
form = CallForm(request.POST, instance=c)
print form.errors
if form.is_valid():
form.save()
return HttpResponseRedirect('/ViewCalls/')
else:
form = CallForm(instance=c)
args = {}
args.update(csrf(request))
args["form"] = form
args["id"] = call_id
t = get_template('edit_call.html')
cont = RequestContext(request, args)
html = t.render(cont)
return HttpResponse(html)
表格: 简单如:
class CallForm (forms.ModelForm):
employee_id = forms.ModelChoiceField(queryset=Employee.objects.all())
status = forms.ModelChoiceField(queryset=Status.objects.all())
class Meta():
model = Call
答案 0 :(得分:2)
每次加载表单时都需要调用构造函数来更新选项。所以表格应该是:
class CallForm(forms.ModelForm):
...
status = forms.ChoiceField()
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=None,
empty_permitted=False):
super(CallForm, self).__init__(data, files, auto_id, prefix, initial, error_class,
label_suffix, empty_permitted)
self.fields['status'].choices = FormsTools.StatusesToTuples(Status.objects.all())
答案 1 :(得分:0)
你看过forms.ModelChoiceField了吗?
更新后的问题更新答案:
您现在需要让您的模型和表单匹配:
您的模型有一个IntegerField,您的表单有一个ModelChoiceField。后者返回一个pk字符串,而不是整数ID。
鉴于您使用的是模型,为什么不让它为您创建字段呢?
class CallForm(forms.ModelForm):
class Meta:
model = Call
fields = ('employee', 'status') # assuming these are what the field names are