【问题标题】:Using value from URL in Form Wizard for Django在 Django 表单向导中使用 URL 中的值
【发布时间】:2021-06-25 09:06:19
【问题描述】:

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

我已尝试根据this thread 重新定义方法 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 很陌生,不知道问题出在哪里。

【问题讨论】:

    标签: python django django-formwizard django-formtools


    【解决方案1】:

    您应该在调用super(SetScopeForm, self).__init__(*args, **kwargs) 之前从kwargs 中删除cliend_id

    要删除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
    

    【讨论】:

      猜你喜欢
      • 2011-09-15
      • 2016-04-09
      • 1970-01-01
      • 2012-05-16
      • 2013-07-29
      • 2013-01-16
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多