简体   繁体   English

将数据从Views.py传递到Forms.py

[英]Pass data from Views.py to Forms.py

I am trying to move data from my views.py to my forms.py pages. 我正在尝试将数据从views.py移到forms.py页面。 I am using the FormWizard, however i dont think it will matter here. 我正在使用FormWizard,但是我认为这并不重要。

views.py views.py

def get_context_data(self, form, **kwargs):
    context = super(CheckoutWizard, self).get_context_data(form=form, **kwargs)
    kwargs = super(CheckoutWizard, self).get_form_kwargs()

    def get_form_kwargs(self):
        kwargs = super(CheckoutWizard, self).get_form_kwargs()
        kwargs.update({'first_name': 'james'})
        kwargs.update({'last_name': 'bond'})
        form = CreditCardForm(kwargs)
        return kwargs

forms.py - in CreditCardForm form.py-在CreditCardForm中

def __init__(self, *args, **kwargs):

    for a in args:
        for key in a:
            print("key: %s , value: %s" % (key, a[key]))

    super(CreditCardForm, self).__init__(*args, **kwargs)

In the forms file above I am accessing the data in *args with the nested loops because if i call args without the * i get this back 在上面的表单文件中,我正在使用嵌套循环访问* args中的数据,因为如果我在不带*的情况下调用args,则会得到此结果

({'first_name': 'james', 'last_name': 'james'},)

which i believe is a tuple with a dictionary in it. 我相信这是其中有字典的元组。

I have seen other solutions where other people are using **kwargs instead. 我已经看到其他人使用** kwargs的其他解决方案。 My current solution feels a bit hacky so if there is a more correct or simpler way of doing this id appreciate the help. 我当前的解决方案感觉有些棘手,因此,如果有更正确或更简单的方法来完成此ID,请多多帮助。 Its also strange to me that in views i am adding to kwargs, but then accessing that data in args. 我也很奇怪,在视图中我要添加到kwargs,然后在args中访问该数据。 Any explanation on the differences would also be appreciated. 关于差异的任何解释也将不胜感激。

Thanks! 谢谢!

def get_form_kwargs(self):
    kwargs = super(CheckoutWizard, self).get_form_kwargs()
    kwargs.update({'first_name': 'james'})
    kwargs.update({'last_name': 'bond'})
    # this will be called by cvb like form_class(**self.get_form_kwargs())
    # because you miss ** so you get your kwargs in arg
    # form = CreditCardForm(**kwargs)
    return kwargs


def __init__(self, *args, **kwargs):
    first_name = kwargs.pop('first_name')
    last_name= kwargs.pop('last_name')
    super(CreditCardForm, self).__init__(*args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM