环境搭建及常见配置
详情可参见Django环境搭建及开发
# 如果同时安装了Python 2和Pyhton 3要指定版本 mkvirtualenv -p python3 env 或 mkvirtualenv --python=python3路径 env pip install django mysqlclient pip install django-crispy-forms django-formtools httplib2
虽然很多领域如机器学习的开发者当前更青睐于Python 2,但Python 3已经被越来越多的开发者们所使用,本文旨在整理Python 3环境下安装最新Django版本所出现的问题,其中有很多内容和Python 2下相似或相同。
1.用户表重写
在继承AbstractUser表重写该类时会提示Reverse accessor for ‘User.*’ clashes with reverse accessor for ‘*.*’
1 2 3 4 |
auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserProfile.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'UserProfile.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'UserProfile.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'UserProfile.user_permissions'. |
解决这一问题只需要按照你定义的app名称和类名在settings.py中添加如下内容:
1 |
AUTH_USER_MODEL = 'appName.ClassName' |
此外添加图片时要按照所提示的安装Pillow
1 2 |
users.UserProfile.avatar: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". |
MySQL Strict Mode && InconsistentMigrationHistory
1 2 3 4 5 6 7 8 9 10 11 |
# 报错 WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. # setttings.py的DATABASES下配置 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", } # 报错 django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency users.0001_initial on database 'default'. # 针对以上报错请备份数据库,删除所有数据表以及migration文件重新执行makemigrations, migrate指令 |
2.settings.py常见配置
1 2 3 4 5 6 7 |
# 将所有新建app合并到apps目录下 sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) # 语言 LANGUAGE_CODE = 'zh-hans' # 时区 TIME_ZONE = 'Asia/Shanghai' USE_TZ = False |
3. Warning: (1366, “Incorrect string value…)
lib/python3.6/site-packages/django/db/backends/mysql/base.py:101: Warning: (1366, “Incorrect string value: ‘\\xE7\\x94\\xA8\\xE6\\x88\\xB7…’ for column ‘name’ at row *”)
出现以上错误是在执行migrate时报出,原因是代码中存在中文,实际测试并不影响数据表的生成。解决方法首先查看数据库是否使用UTF-8编码(Python 3),然后可尝试在中文字符的引号前添加u或在文件头添加# coding:utf-8(Python 2),报错中的Unicode为“用户”二字,如何进行输出呢?
1 2 3 4 5 6 7 8 |
# Python 2 # coding:utf-8 a = '\xE7\x94\xA8\xE6\x88\xB7' print a # Python 3 a = '\xE7\x94\xA8\xE6\x88\xB7' a = a.encode('raw_unicode_escape').decode() print (a) |
4. CSRF verification failed. Request aborted.
在form表单内部添加{% csrf_token %}
5.error: command ‘clang’ failed with exit status 1(pymssql)
Failed building wheel for pymssql
MacOS解决方法:
1 2 3 |
brew unlink freetds; brew install freetds@0.91; brew link --force freetds@0.91 |
6.安装Pillow缺少zlib的问题
1 2 3 |
ValueError: zlib is required unless explicitly disabled using --disable-zlib, aborting # 执行 xcode-select --install |
7.django.db.utils.OperationalError: (1050, “Table ‘xxx’ already exists”)
这通常是由于删除 migrations 目录下迁移记录以及django_migrations表中对应内容,但数据表中仍存在该字段所致,在 migrate 时添加–fake 参数可解决这一问题
1 |
python manage.py migrate appName --fake |
8.RuntimeError: Model class apps.xxx.models.xxx doesn’t declare an explicit app_label and isn’t in an application in INSTALLED_APPS.
1 2 3 4 |
# 将对应的 apps.py 下的 name = 'xxxx' # 修改为 name = 'apps.xxxx' |
这是由于我将的有 app 提取到 apps 目录下产生的名称冲突所致
9.Google分析等线上才使用的代码如何在线下进行屏蔽?
一种比较简单的方式是通过 debug的配置来进行区分
1 2 3 4 5 6 7 8 9 10 11 12 |
# settings.py DEBUG = True INTERNAL_IPS = ( '127.0.0.1', 'localhost', ) # 然后在 template 中使用 {% if not debug %} # 生产环境才需要加载的内容 {% endif %} |
10.django.db.utils.OperationalError: (1071, ‘Specified key was too long; max key length is 767 bytes’)
1 |
ALTER DATABASE `databasename` CHARACTER SET utf8; |