Home > other >  get() takes 1 positional argument but 2 were given when trying to override save method in django
get() takes 1 positional argument but 2 were given when trying to override save method in django

Time:10-25

how to fix this?

from django.db import models
import pycountry
# Create your models here.
class Country(models.Model):
    country_name = models.CharField(max_length=50)
    code = models.CharField(max_length=3, editable=False)

    

    def save(self, *args, **kwargs):
        country_list = []
        for country in pycountry.countries:
            country_list.append(country.name)
        if (self.country_name in country_list):
            self.code = pycountry.countries.get(self.country_name).alpha_3
            super(Country, self).save(*args, **kwargs)

CodePudding user response:

I peeked at the pycountry API. The get method signature on the countries object ultimately looks like this:

def get(self, **kw):
    ...

In Python speak that means it only accepts "named" arguments. In your code, you're giving the country_name as a positional argument.

I couldn't infer from my quick glance at the code what they're expecting you to pass, but from context I'm guessing it's something like this:

self.code = pycountry.countries.get(name=self.country_name).alpha_3

Notice the slight difference where your argument is explicitly named, not just passed positionally.

This error itself is always a tad confusing because of self. Python instance methods always have self as an implicit positional argument. It's telling you that self is the only valid positional argument (1), but you are passing both self and country_name positionally (2).

  • Related