Adding ** kwarg to the class

class StatusForm(ModelForm):

    bases = forms.ModelMultipleChoiceField(
            queryset=Base.objects.all(),  #this should get overwritten
            widget=forms.SelectMultiple,
        )

    class Meta:
        model = HiringStatus
        exclude = ('company', 'date')

    def __init__(self, *args, **kwargs):
        super(StatusForm, self).__init__(*args, **kwargs)
        if kwargs.has_key('bases_queryset'):
            self.fields['bases'].queryset = kwargs['bases_queryset']

I want to add an option to this form that allows me to create such a form:

form = StatusForm(bases_queryset=Base.objects.filter([...])

But somehow I need to β€œadd” this keyword argument to the class so that it is recognized. Now they, as now, I just get this error:

__init__() got an unexpected keyword argument 'bases_queryset'

+3
source share
2 answers

This is because you are unpacking kwargs into a super constructor. Try this before calling super:

if kwargs.has_key('bases_queryset'):
    bases_queryset = kwargs['bases_queryset']
    del kwargs['bases_queryset']

but this is not an ideal solution ...

+11
source

As @Keeper points out, you shouldn't pass your β€œnew” keyword arguments to the superclass. The best thing to do before you call super __init__:

bqs = kwargs.pop('bases_queryset', None)

__init__, if bqs is not None: has_key ( bqs kwargs['bases_queryset'], ).

" " . , , ( ;-), , , , "" (.. no **k). :

import inspect

def selective_call(func, **kwargs):
    names, _, _, _ = inspect.getargspec(func)
    usable_kwargs = dict((k,kwargs[k]) for k in names if k in kwargs)
    return func(**usable_kwargs)

, __init__ __init__, selective_call(super_init, **kwargs) "". (, , , , ...! -)

+11

Source: https://habr.com/ru/post/1710346/


All Articles