try/db.py", line 22, in __getattr__ raise AttributeError AttributeError

557 views
Skip to first unread message

Eve Pokua

unread,
Dec 3, 2016, 2:25:44 AM12/3/16
to django-oscar
Hello,

I have been struggling to resolve this problem.

I am following the setup -


Which was not bad till I got this this point.

Initial data


python manage.py oscar_populate_countries

I was able to install the -
pip install pycountry

with success.
I am using mysql -installed the adapter-
DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.mysql", # DB name or path to database file if using sqlite3. "NAME": "mydatabase", # Not used with sqlite3. "USER": "muuser", # Not used with sqlite3. "PASSWORD": "mypassword", # Set to empty string for localhost. Not used with sqlite3. "HOST": "localhost", # Set to empty string for default. Not used with sqlite3. "PORT": "myportnumber", 'ATOMIC_REQUESTS': True, } }



Other settings that might raise an interest -

# Full filesystem path to the project.
PROJECT_APP_PATH
= os.path.dirname(os.path.abspath(__file__))
PROJECT_APP
= os.path.basename(PROJECT_APP_PATH)
PROJECT_ROOT
= BASE_DIR = os.path.dirname(PROJECT_APP_PATH)

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL
= '/static/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT
= os.path.join(PROJECT_ROOT, STATIC_URL.strip("/"))

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL
= STATIC_URL + "media/"

HAYSTACK_CONNECTIONS
= {
 
'default': {
 
'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
 
'URL': 'http://127.0.0.1:8983/solr',
 
'INCLUDE_SPELLING': True,
 
},
}


i have installed south -

Successfully built south

 

Installing collected packages: south




try/db.py", line 22, in __getattr__



 

    raise AttributeError

 

AttributeError



(oscar_env) ..... python manage.py startapp myapp



 

......oscar_env/lib/python2.7/site-packages/django/utils/six.py:808: RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead.

 

 
return meta(name, bases, d)




I have removed a few things I do not want made in public but hope the main problem is explained well.


I also this the following to see if the error would be resolve but still got it.


pip install -U --force-reinstall django







 



Collecting django

 

 
Downloading Django-1.10.4-py2.py3-none-any.whl (6.8MB)

 

   
100% |████████████████████████████████| 6.8MB 75kB/s

 

Installing collected packages: django

 

 
Found existing installation: Django 1.9.11

 

   
Uninstalling Django-1.9.11:

 

     
Successfully uninstalled Django-1.9.11

 

Successfully installed django-1.10.4





So far I have uninstalled django-oscar and trying to make a start again.


I downloaded the following -


https://github.com/django-oscar/django-oscar-stores


and


https://github.com/django-oscar/django-oscar



Don't know if I can play around it to make sense of it.


Any reason why I am having this error ?




Thanking you.

Eve Pokua

unread,
Dec 4, 2016, 4:57:28 PM12/4/16
to django-oscar
Hello,

I am able to load the application but calling this -

./manage.py oscar_populate_countries


still throws this error


pycountry/db.py", line 22, in __getattr__

    raise AttributeError

AttributeError


Please, help as I have been googling for days now.


Thank you.


Regards

Eve Pokua

unread,
Dec 4, 2016, 4:59:16 PM12/4/16
to django-oscar

Jim Bernatowicz

unread,
Dec 6, 2016, 12:02:40 PM12/6/16
to django-oscar
Coincidentally I ran into this yesterday.  I hacked site-packages/oscar/management/commands/oscar_populate_countried.py to reflect:

        countries = [
            Country(
                iso_3166_1_a2=country.alpha_2, # note the underscore
                iso_3166_1_a3=country.alpha_3, # note the underscore
                iso_3166_1_numeric=country.numeric,
                printable_name=country.name,
                name=getattr(country, 'official_name', ''),
                is_shipping_country=options['is_shipping'])
            for country in pycountry.countries]

Perhaps a new version of pycountries came out recently with new attribute names?

Hope this get you unstuck.

Thanks,
Jim

Eve Pokua

unread,
Dec 7, 2016, 1:27:24 AM12/7/16
to django-oscar
Thank you. I will look into this.

Eve Pokua

unread,
Dec 7, 2016, 5:38:06 AM12/7/16
to django-oscar
Hello,


I have taken a look at your code again mine.  First of all here is my installs -


Babel==2.3.4
Django==1.9.12
django
-appconf==1.0.2
django
-compressor==2.1
django
-extra-views==0.6.4
django
-haystack==2.5.1
django
-localflavor==1.3
django
-oscar==1.3
django
-oscar-paypal==0.9.7
django
-tables2==1.0.7
django
-treebeard==4.1.0
django
-widget-tweaks==1.4.1
factory
-boy==2.7.0
fake
-factory==0.7.2
funcsigs
==1.0.2
ipaddress
==1.0.17
mock
==2.0.0
MySQL-python==1.2.5
pbr
==1.10.0
phonenumbers
==7.7.5
Pillow==3.4.2
purl
==1.3
pycountry
==16.11.27.1
python
-dateutil==2.6.0
pytz
==2016.7
rcssmin
==1.0.6
requests
==2.12.3
rjsmin
==1.0.12
six
==1.10.0
sorl
-thumbnail==12.4a1
Unidecode==0.4.19




Secondly, the error is coming from the pycountry.py file as log in at line 22.

And the error is -

./manage.py oscar_populate_countries

 

/Users/akos/oscar/lib/python2.7/site-packages/django/utils/six.py:808: RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead.

 
return meta(name, bases, d)


 

/Users/akos/oscar/lib/python2.7/site-packages/django/core/management/__init__.py:345: RemovedInDjango110Warning: OptionParser usage for Django management commands is deprecated, use ArgumentParser instead

 
self.fetch_command(subcommand).run_from_argv(self.argv)


 

Traceback (most recent call last):

 
File "./manage.py", line 10, in <module>

    execute_from_command_line
(sys.argv)

 
File "/Users/akos/oscar/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line

    utility
.execute()

 
File "/Users/akos/oscar/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute

   
self.fetch_command(subcommand).run_from_argv(self.argv)

 
File "/Users/akos/oscar/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv

   
self.execute(*args, **cmd_options)

 
File "/Users/akos/oscar/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute

    output
= self.handle(*args, **options)

 
File "/Users/akos/oscar/lib/python2.7/site-packages/oscar/management/commands/oscar_populate_countries.py", line 58, in handle

   
for country in pycountry.countries]

 
File "/Users/akos/oscar/lib/python2.7/site-packages/pycountry/db.py", line 22, in __getattr__

   
raise AttributeError

AttributeError



And my /Users/akos/oscar/lib/python2.7/site-packages/pycountry/db.py

# vim:fileencoding=utf-8


from io import open
import logging
import json


logger
= logging.getLogger('pycountry.db')


try:
    unicode
except NameError:
    unicode
= str




class Data(object):


   
def __init__(self, **fields):
       
self._fields = fields


   
def __getattr__(self, key):
       
if key not in self._fields:
           
raise AttributeError
       
return self._fields[key]


   
def __setattr__(self, key, value):
       
if key != '_fields':
           
self._fields[key] = value
       
super(Data, self).__setattr__(key, value)


   
def __repr__(self):
        cls_name
= self.__class__.__name__
        fields
= ', '.join('%s=%r' % i for i in sorted(self._fields.items()))
       
return '%s(%s)' % (cls_name, fields)


   
def __dir__(self):
       
return dir(self.__class__) + list(self._fields)




def lazy_load(f):
   
def load_if_needed(self, *args, **kw):
       
if not self._is_loaded:
           
self._load()
       
return f(self, *args, **kw)
   
return load_if_needed




class Database(object):


    data_class_base
= Data
    data_class_name
= None
    root_key
= None
    no_index
= []


   
def __init__(self, filename):
       
self.filename = filename
       
self._is_loaded = False


   
def _load(self):
       
self.objects = []
       
self.index_names = set()
       
self.indices = {}


       
self.data_class = type(
           
self.data_class_name, (self.data_class_base,), {})


       
with open(self.filename, 'r', encoding="utf-8") as f:
            tree
= json.load(f)


       
for entry in tree[self.root_key]:
            obj
= self.data_class(**entry)
           
self.objects.append(obj)
           
# Inject into index.
           
for key, value in entry.items():
               
if key in self.no_index:
                   
continue
                index
= self.indices.setdefault(key, {})
               
if value in index:
                    logger
.debug(
                       
'%s %r already taken in index %r and will be '
                       
'ignored. This is an error in the databases.' %
                       
(self.data_class_name, value, key))
                index
[value] = obj


       
self._is_loaded = True


   
# Public API


   
@lazy_load
   
def __iter__(self):
       
return iter(self.objects)


   
@lazy_load
   
def __len__(self):
       
return len(self.objects)


   
@lazy_load
   
def get(self, **kw):
       
if len(kw) != 1:
           
raise TypeError('Only one criteria may be given')
        field
, value = kw.popitem()
       
return self.indices[field][value]


   
@lazy_load
   
def lookup(self, value):
       
# try relatively quick exact matches first
       
if isinstance(value, (str, unicode)):
            value
= value.lower()


       
for key in self.indices:
           
try:
               
return self.indices[key][value]
           
except LookupError:
               
pass
       
# then try slower case-insensitive lookups
       
for candidate in self:
           
for v in candidate._fields.values():
               
if v is None:
                   
continue
               
if v.lower() == value:
                   
return candidate
       
raise LookupError('Could not find a record for %r' % value)









My  /Users/akos/oscar/lib/python2.7/site-packages/oscar/management/commands/oscar_populate_countries.py", line 58, in handle

# -*- coding: utf-8 -*-
import sys
from optparse import make_option


from django.core.management.base import BaseCommand, CommandError


from oscar.core.loading import get_model


Country = get_model('address', 'Country')




class Command(BaseCommand):
    help
= "Populates the list of countries with data from pycountry."
   
# TODO: Allow setting locale to fetch country names in right locale
   
# https://code.djangoproject.com/ticket/6376


    option_list
= BaseCommand.option_list + (
        make_option
(
           
'--no-shipping',
            action
='store_false',
            dest
='is_shipping',
           
default=True,
            help
="Don't mark countries for shipping"),
        make_option
(
           
'--initial-only',
            action
='store_true',
            dest
='is_initial_only',
           
default=False,
            help
="Exit quietly without doing anything if countries were already populated."),
   
)


   
def handle(self, *args, **options):
       
try:
           
import pycountry
       
except ImportError:
           
raise CommandError(
               
"You are missing the pycountry library. Install it with "
               
"'pip install pycountry'")


       
if Country.objects.exists():
           
if options.get('is_initial_only', False):
               
# exit quietly, as the initial load already seems to have happened.
               
self.stdout.write("Countries already populated; nothing to be done.")
                sys
.exit(0)
           
else:
               
raise CommandError(
                   
"You already have countries in your database. This command "
                   
"currently does not support updating existing countries.")


       
countries = [
           
Country(
                iso_3166_1_a2
=country.alpha2,
                iso_3166_1_a3
=country.alpha3,

                iso_3166_1_numeric
=country.numeric,
                printable_name
=country.name,
                name
=getattr(country, 'official_name', ''),
                is_shipping_country
=options['is_shipping'])
           
for country in pycountry.countries]



       
Country.objects.bulk_create(countries)
       
self.stdout.write("Successfully added %s countries." % len(countries))



What you are suggesting to hack is in bold above. and so why this error?  It's no difference to yours.

I did file an issue a couple of days ago. And they seem to be looking at it -



and so what I'm doing wrong again?


Thank you so much for looking into this and sharing.

Regards


On Tuesday, 6 December 2016 17:02:40 UTC, Jim Bernatowicz wrote:

Eve Pokua

unread,
Dec 7, 2016, 5:45:06 AM12/7/16
to django-oscar
Hello,

Sorry, it didn't load all the messages I was sending here is the 

= [

           
Country(

                iso_3166_1_a2
=country.alpha2,

                iso_3166_1_a3
=country.alpha3,

                iso_3166_1_numeric
=country.numeric,


                printable_name
=country.name,

                name
=getattr(country, 'official_name', ''),

                is_shipping_country
=options['is_shipping'])

           
for country in pycountry.countries]





       
Country.objects.bulk_create(countries)




       
self.stdout.write("Successfully added %s countries." % len(countries))



There's no difference between your code and mine above so what is going on?

Regards






On Tuesday, 6 December 2016 17:02:40 UTC, Jim Bernatowicz wrote:

Eve Pokua

unread,
Dec 7, 2016, 6:10:45 AM12/7/16
to django-oscar
Hello,

I did file an issue with the django-oscar team because, I do believe it's a bug.


And the team seems to be doing something about it. I believe


meaning I may have to wait for the pycountry.py release?


Regards



On Saturday, 3 December 2016 07:25:44 UTC, Eve Pokua wrote:

Eve Pokua

unread,
Dec 7, 2016, 8:49:46 AM12/7/16
to django-oscar


Hello Jim,

I took a look at your code below again, 

 iso_3166_1_a2=country.alpha_2, # note the underscore
 iso_3166_1_a3=country.alpha_3, # note the underscore


and yes I hacked it. corrected. 
I have another error but that's another story.

Thank you.


Regards

On Tuesday, 6 December 2016 17:02:40 UTC, Jim Bernatowicz wrote:
Reply all
Reply to author
Forward
0 new messages