Search code examples
pythondjangokeyword-argument

Django: Passing **kwargs


I have a question regarding passing **kwargs. In views.py I am collecting data such as order_id etc. This data I am passing to the charge function from where I call the ChargeManager. For each def I am passing currently the kwargs. However, I hoped to find a way that I only have to write it once in views.py. And then I can just use **kwargs to collect the data and pass them. However whatever I am trying I am struggling to get it working. Do you have any ideas why?

Example how I wanted it to work:

1)

paid = instance.charge(order_id=session_order_id, total=total, token=token)

2) models.py:

TransactionProfile
    def charge(self, **kwargs):
        return Charge.objects.stripe_charge(self, order_id, total, token)

3) models.py:

ChargeManager
    def stripe_charge(self, **kwargs): 
        print(order_id)

Currently, I have to do it this way:

views.py

paid = instance.charge(order_id=session_order_id, total=total, token=token)

models.py

def charge(self, order_id, total, token):
    return Charge.objects.stripe_charge(self, order_id, total, token)

models.py:

TransactionProfile
    def charge(self, order_id, total, token):
        return Charge.objects.stripe_charge(self, order_id, total, token)

models.py:

ChargeManager
    def stripe_charge(self, transaction_profile, order_id, total, token):

Solution

  • If your function accepts kwargs you can call another method with the same kwargs:

    def charge(self, **kwargs):
        return Charge.objects.stripe_charge(self, transaction_profile=self, **kwargs)
    

    If your stripe_charge method only accepts kwargs, you can no longer use print(order_id). You've got to fetch it from kwargs:

    def stripe_charge(self, **kwargs): 
        print(kwargs['order_id'])
    

    I'm not sure I'd encourage you to use **kwargs like this. When I see the method def charge(self, order_id, total, token): it's immediately clear how to call it. def charge(self, **kwargs) is less clear.