Django:在init中访问form_kwargs

时间:2018-11-21 14:29:30

标签: python django

我定义了form_kwargs,并且可以直接在__init__中的form.py中访问它们。我希望做organizer = kwargs.pop('organizer')等。有人能解释一下为什么为什么我可以直接访问这些kwarg,即使它们应该存储在form_kwargs内吗?

我目前正在尝试将此行为复制到我的class BaseReserveFormSet(BaseFormSet):,但是如果没有kwargs.pop,我将无法访问它们

@cached_property
    def formset(self):
        ReserveFormSet = formset_factory(
            ReserveForm,
            formset=BaseReserveFormSet,
            extra=0
        )

        return ReserveFormSet(
            data=(
                self.request.POST
                if self.request.method == 'POST'
                else None
            ),
            initial=self.tickets,
            form_kwargs={
                'organizer': self.request.organizer,
                'event': self.request.event,
                'user_order_reference': self.request.session.get('order_reference'),
                'discount_code_session': self.discount_code,
            }
        )

forms.py

class BaseReserveFormSet(BaseFormSet):

    def __init__(self, *args, **kwargs):
        self.discount_code_session = kwargs['form_kwargs']['discount_code_session']
        self.event = kwargs['form_kwargs']['event']
        # print(kwargs.pop('discount_code_session'))  # Why does this not work?
        super().__init__(*args, **kwargs)    

class ReserveForm(forms.ModelForm):
        class Meta:
            model = ReservedItem
            fields = ['ticket', 'quantity']

        def __init__(self, organizer, event, user_order_reference,
                     discount_code_session, *args, **kwargs):
            self.organizer = organizer
            self.event = event
            [...]

1 个答案:

答案 0 :(得分:3)

def __init__(self, organizer, event, user_order_reference,
             discount_code_session, *args, **kwargs):
    self.organizer = organizer
    self.event = event

函数签名中有organizerevent等,因此您可以分别以organizerevent的方式访问它们。

如果您不将它们包括在函数签名中,则可以从kwargs中访问它们。

def __init__(self, *args, **kwargs):
    self.organizer = kwargs.pop('organizer')
    self.event = kwargs.pop('event')

在您的BaseReserveFormSet中,kwargs.pop('discount_code_session')不起作用,因为您没有将discount_code_session传递给表单集,而是将其包括在form_kwargs词典中。

如果您希望能够从discount_code_session的{​​{1}}中弹出kwargs

BaseReserveFormSet

然后在您的视图中将其作为单独的kwarg传递。请注意,表单集将不再将其传递给表单,因为它不再位于class BaseReserveFormSet(BaseFormSet): def __init__(self, *args, **kwargs): self.discount_code_session = kwargs['form_kwargs']['discount_code_session'] self.event = kwargs['form_kwargs']['event'] self.discount_code_session = kwargs.pop('discount_code_session')) super().__init__(*args, **kwargs) 中。

form_kwargs