pythondjangopython-2.7python-3.xbackport

Backporting from 3 to 2.7: ImportError: cannot import name


After reading this, and crying a lot, I'm trying to make my Django app work with Python 2.7.

Here's my Django web dir:

├── locale
│   ├── en
│   ├── fr
│   └── sv
├── produits
│   ├── migrations
│   └── templatetags
├── pyweb
├── templates
│   └── produits
├── third_party
│   ├── authomatic_0_1_0
│   ├── defusedxml-0.4.1
│   ├── google_appengine_1_9_25
│   ├── python-openid_2_2_5
│   └── python3-openid
└── uploads

The most important to notice is that I've tried to add all my "external" module into a folder third_party.

In my views.py, the following code was working:

from third_party.authomatic_0_1_0 import authomatic
from third_party.authomatic_0_1_0.authomatic import adapters
from third_party.authomatic_0_1_0.authomatic.providers import oauth1, oauth2

It was working because I added those lines in settings.py at the very beginning:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR+'/third_party/defusedxml-0.4.1')
sys.path.append(BASE_DIR+'/third_party/python3-openid')
sys.path.append(BASE_DIR+'/third_party/google_appengine_1_9_25')
sys.path.append(BASE_DIR+'/third_party/authomatic_0_1_0')

But now, with python 2.7 it doesnt work anymore. What should I do to make it work? And what is a good practice in Python (because Pycharm doesn't recognize all the subfolders of third_party)?


Solution

  • Two problems: (1) encoding, so I added in all files at the very beginning:

    # coding=UTF-8
    

    (2) Decorator python_2_unicode_compatible: needed this for all my models with __str__ implemented, for example:

    @python_2_unicode_compatible
    class Texte(models.Model):
        texte = models.CharField(max_length=200)
    
        def __str__(self):
            return self.texte
    

    See here for more information