【问题标题】:Backporting from 3 to 2.7: ImportError: cannot import name从 3 向后移植到 2.7:ImportError: cannot import name
【发布时间】:2015-09-01 12:59:22
【问题描述】:

在阅读了this 并哭了很多之后,我正在尝试让我的 Django 应用程序与 Python 2.7 一起工作。

这是我的 Django 网络目录:

├── 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

最需要注意的是,我已尝试将所有“外部”模块添加到文件夹 third_party

在我的views.py 中,以下代码正在运行:

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

它正在工作因为我在一开始就在settings.py 中添加了这些行

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')

但是现在,使用 python 2.7 它不再工作了。我应该怎么做才能让它工作?在 Python 中有什么好的做法(因为 Pycharm 不能识别third_party 的所有子文件夹)?

【问题讨论】:

  • 您是否考虑过在包中添加__init__.py 以使third_party 成为一个包?大概每个子目录都已经是一个了?
  • 你能把你得到的完整错误贴出来吗?
  • @jonrsharpe 你发现了错误!我可以请你回答它,我会检查是否有效?谢谢

标签: python django python-2.7 python-3.x backport


【解决方案1】:

两个问题:(1)编码,所以我一开始就加在所有文件里:

# coding=UTF-8

(2) 装饰器python_2_unicode_compatible:我所有实现了__str__ 的模型都需要这个,例如:

@python_2_unicode_compatible
class Texte(models.Model):
    texte = models.CharField(max_length=200)

    def __str__(self):
        return self.texte

更多信息请参见here

【讨论】:

    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 2019-07-20
    相关资源
    最近更新 更多