1

我正在尝试使用此表单向导在 Django 中设计多页表单。我需要从 URL 中捕获一个值,它是客户端的 ID,并将其传递给 Forms 实例之一,因为表单将使用该客户端的特定值动态构建。

我已经尝试根据这个线程重新定义方法 get_form_kwargs ,但这对我不起作用。我的views.py中有以下代码:

class NewScanWizard(CookieWizardView):
    def done(self, form_list, **kwargs):
        #some code
    
    def get_form_kwargs(self, step):
        kwargs = super(NewScanWizard, self).get_form_kwargs(step)
        if step == '1': #I just need client_id for step 1
            kwargs['client_id'] = self.kwargs['client_id']

        return kwargs

然后,这是 forms.py 中的代码:

from django import forms
from clients.models import KnownHosts
from bson import ObjectId

class SetNameForm(forms.Form): #Form for step 0
    name = forms.CharField()

class SetScopeForm(forms.Form): #Form for step 1, this is where I need to get client_id
    def __init__(self, *args, **kwargs):
        
        super(SetScopeForm, self).__init__(*args, **kwargs)
        client_id = kwargs['client_id']
        clientHosts = KnownHosts.objects.filter(_id=ObjectId(client_id))

        if clientHosts:
            for h in clientHosts.hosts:
                #some code to build the form

运行此代码时,步骤 0 完美运行。但是,在提交第 0 部分并获取第 1 部分时,我收到以下错误:

_ init_ () 得到了一个意外的关键字参数“client_id”

我做了一些调试,我可以看到 client_id 的值正确绑定到 kwargs,但我不知道如何解决这个问题。我认为这可能不难解决,但我对 Python 还是很陌生,不知道问题出在哪里。

4

1 回答 1

0

您应该在调用之前删除cliend_idfrom 。kwargssuper(SetScopeForm, self).__init__(*args, **kwargs)

要删除client_id,您可以使用kwargs.pop('client_id', None)

class SetScopeForm(forms.Form): #Form for step 1, this is where I need to get client_id
    def __init__(self, *args, **kwargs):
        # POP CLIENT_ID BEFORE calling super SetScopeForm
        client_id = kwargs.pop('client_id', None)
        # call super
        super(SetScopeForm, self).__init__(*args, **kwargs)
        clientHosts = KnownHosts.objects.filter(_id=ObjectId(client_id))

        if clientHosts:
            for h in clientHosts.hosts:
                #some code to build the form
于 2021-03-29T10:28:37.187 回答