簡體   English   中英

Django動態表單-動態ChoiceField

[英]django dynamic forms - Dynamic ChoiceField

在django中,我如何使每次調用數據庫時都可以選擇一個formField來訪問該數據庫? 現在,行: status = forms.ChoiceField(choices=FormsTools.StatusesToTuples(Status.objects.all()))在加載django之后執行,而不是在每次顯示表單時執行。 如何使該領域充滿活力? 所以每次顯示表單時,selectable字段都會有來自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

每次加載表單以更新選擇時,都需要調用構造函數。 因此,表單應為:

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

你看過form.ModelChoiceField嗎?

更新后的問題:

現在,您需要使模型和表單匹配:

您的模型有一個IntegerField,您的窗體有一個ModelChoiceField。 后者返回一個pk字符串,而不是整數ID。

鑒於您正在使用模型表單,為什么不讓它為您創建字段呢?

class CallForm(forms.ModelForm):

    class Meta:
        model = Call
        fields = ('employee', 'status')  # assuming these are what the field names are

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM