Alan Hou的个人博客

Django环境搭建及开发

开发工具:PyCharm

 

环境配置

#mac下环境配置
sudo easy_install pip
sudo -H pip install virtualenv
sudo easy_install virtualenvwrapper
source /usr/local/bin/virtualenvwrapper.sh //可加入.bash_profile等文件启动执行,找不到可通过sudo find / -name virtualenvwrapper.sh查找
# 在.bash_profile或.bashrc下还可配置默认虚拟环境存放路径
export WORKON_HOME=$HOME/.virtualenvs # windows下添加WORKON_HOME环境变量
mkvirtualenv env1
//切换虚拟环境
workon env1
pip install django //指定版本sudo -H pip install Django==1.9.8
//安装MySQL组件
pip install mysql-python
//退出虚拟环境
deactivate
//其它命令
lsvirtualenv -b
lssitepackages
cdvirtualenv
cdsitepackages
rmvirtualenv env1
cpvirtualenv env1 env2
#安装Xadmin,需在settings.py的INSTALLED_APPS添加xadmin, crispy_forms
pip install xadmin
#Captcha
pip install  django-simple-captcha==0.4.6

注:
手动源码安装xadmin时需额外安装依赖包

pip install django-crispy-forms django-formtools httplib2

使用多Python版本需要指定版本:

#设置别名(.bash_profile),如
alias python3='/Users/alan/anaconda/bin/python3.5'
#默认Python 2
mkvirtualenv -p python env4
或
mkvirtualenv --python=python2路径 env4
#Python 3
mkvirtualenv -p python3 env5
或
mkvirtualenv --python=python3路径 env5

 

注:使用Anaconda搭建虚拟环境

conda search "^python$"
conda create -n yourenvname python=x.x anaconda
conda info -e
source activate yourenvname
source deactivate
conda remove -n yourenvname -all

常用命令

#创建项目
django-admin startproject myproject
#创建应用
cd myproject
python manage.py startapp blog
#PyCharm Run manage.py Task或在命令切的到目录执行python manage.py ...
#创建应用,如message,创建后需在settings.py的INSTALLED_APPS中进行添加
startapp message
#先配置settings.py中DATABASES的参数
#        'ENGINE': 'django.db.backends.mysql',
#        'NAME': 'dbname',
#        'USER': 'root',
#        'PASSWORD': 'password',
#        'HOST': '127.0.0.1',
makemigrations
migrate
runserver
#创建后台管理员账号
createsuperuser

小技巧:
执行python manage.py sqlmigrate 应用名(如mesage) 0001(migrations文件夹下的序号)可以查看原生的SQL的语句
执行migrate指令后默认生成的表格:

xadmin操作

adminx.py配置

注:在后台如需导出excel格式文件需安装xlwt(pip install xlwt),如需导出xlsx格式的则请安装xlsxwriter

#可选择不同主题
class BaseSetting(object):
    enable_themes = True 
    use_bootswatch = True
#注册配置
xadmin.site.register(views.BaseAdminView, BaseSetting)

class GlobalSettings(object):
    site_title = "后台管理系统" #设置后台左上角名称
    site_footer = "Alan Hou"   #设置后台footer的文字
    menu_style = "accordion"   #左侧导航的收缩显示
xadmin.site.register(views.CommAdminView, GlobalSettings)

将后台中主菜单的英文修改为中文,以app名users为例

#apps的UsersConfig类下添加
verbose_name = u"用户信息"
#__init__.py下添加
default_app_config = "users.apps.UsersConfig"

xadmin中的延伸配置

#后台默认排序
ordering = ['-click_nums']
#后台不可修改字段
readonly_fields = ['click_nums']
#后台隐藏字段
exclude = ['fav_nums']
#可以ajax请求的外键(后台中搜索)
relfield_style = 'fk-ajax'

Model及数据库操作

models.py部分内容示例

#执行makemigrations, migrate指令会进行创建、修改和删除的操作
class UserMessage(models.Model):
    object_id = models.CharField(max_length=50, default="", primary_key=True, verbose_name=u'主键')
    name = models.CharField(max_length=20, null=True, blank=True, default="", verbose_name=u'用户名')
    email = models.EmailField(verbose_name=u'邮箱')
    address = models.CharField(max_length=100, verbose_name=u'联系地址')
    message = models.CharField(max_length=500, verbose_name=u'留言信息')

    # 常用Field类型
    # models.ForeignKey
    # models.DateTimeField
    # models.IntegerField
    # models.IPAddressField
    # models.FileField
    # models.ImageField

    class Meta:
        verbose_name = u'用户留言信息'
        verbose_name_plural = verbose_name
        # db_table = '' 指定数据表名
        # ordering = '-object_id' 默认排序

AutoField, BigAutoField, BigIntegerField, BinaryField, BooleanField, CharField, CommaSeparatedIntegerField, DateField, DateTimeField, DecimalField, DurationField, EmailField, FileField, FileField and FieldFile, FilePathField, FloatField, ImageField, IntegerField, GenericIPAddressField, NullBooleanField, PositiveIntegerField, PositiveSmallIntegerField, SlugField, SmallIntegerField, TextField, TimeField, URLField, UUIDField, ForeignKey, ManyToManyField, OneToOneField

 

null, blank, choices, db_column, db_index, db_tablespace, default, editable, error_messages, help_text, primary_key, unique, unique_for_date, unique_for_month, unique_for_year, verbose_name, validators

views.py中原生SQL语句示例

# 原生SQL语言
# def book_list(request):
#     db = MySQLdb.connect(user='root', db='djangoT', passwd='', host='127.0.0.1')
#     cursor = db.cursor()
#     cursor.execute('SELECT name FROM books ORDER BY name')
#     name = [row[0] for row in cursor.fetchall()]
#     db.close()

注:代码中使用中文需在文件开始指定编码为utf-8

 # -*- coding: utf-8 -*-

表单提交数据需添加

#不添加提交表单会提示CSRF token missing or incorrect.
{% csrf_token %}

如果创建应用比较多,可以创建一个apps的package,把所有应用放在里面,但这样会要求有import时前面加上一个apps,在PyCharm中把apps右键Mark为Sources Root,在settings.py中加入以下代码以避免在命令行中执行时报错

import sys
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))

常见问题

1.Bad Request (400)
需配置项目下的settings.py中的ALLOWED_HOSTS,如下例局域网中可通过http://192.168.1.3:9999进行访问

#启动服务,可指定任意未占用的端口
python manage.py runserver 0.0.0.0:9999
#settings.py
ALLOWED_HOSTS=['192.168.1.3']

2.libmysqlclient.18.dylib问题

Reason: unsafe use of relative rpath libmysqlclient.18.dylib in /Users/alan/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.12-intel.egg-tmp/_mysql.so with restricted binary

#网上多数人给出的解决方案,我的机器上使用未解决
sudo install_name_tool -change libmysqlclient.18.dylib \
/usr/local/mysql/lib/libmysqlclient.18.dylib \
/Users/alan/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.12-intel.egg-tmp/_mysql.so

3.Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
参见Stackoverflow上的回答

P.S.操作别忘了备份数据库哦

4.ValueError: unknown locale: UTF-8

raise ValueError('unknown locale: %s' % localename)
ValueError: unknown locale: UTF-8

在.bash_profile或其它文件中添加如下并source

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

5.pip install速度过慢
在安装时会出现速度太慢,甚至导致无法完成的现象,这时可尝试进行如下配置

cd ~
mkdir .pip
cd .pip
vi pip.conf 
#放入如下内容保存退出
[global]  
index-url = https://pypi.doubanio.com/simple/  
[install]  
trusted-host=pypi.doubanio.com  
disable-pip-version-check = true  
timeout = 6000  

也可在安装时直接使用
pip install -i https://pypi.doubanio.com/simple/ xxx

6.Error fetching command ‘collectstatic’
运行manage.py任务时出现如下报错,并未发现影响到使用

Error fetching command 'collectstatic': You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
Command 'collectstatic' skipped

如需解决,在settings.py中添加

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

7.IntegrityError: (1452, ‘Cannot add or update a child row:
在使用Django Admin后台添加用户时出现如下报错:

IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (<code>mxonine</code>.<code>django_admin_log</code>, CONSTRAINT <code>django_admin_log_user_id_c564eba6_fk_auth_user_id</code> FOREIGN KEY (<code>user_id</code>) REFERENCES <code>auth_user</code> (<code>id</code>))')
[26/Dec/2016 19:50:05] &quot;POST /admin/users/userprofile/add/ HTTP/1.1&quot; 500 196219

一个解决方案是在settings.py的DATABASES版块添加如下代码取消外键检查

'OPTIONS': {
         "init_command": "SET foreign_key_checks = 0;",
    },

8.页面样式(静态文件)导入不成功,在settings.py的最后加入

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

9.表单input中显示None
在value中添加default_if_none,这样就会显示placeholder中的内容

value="{{ forget_form.email.value|default_if_none:'' }}"

10.global name ‘_’ is not defined
添加

from django.utils.translation import ugettext as _

11.dyld: Library not loaded: @rpath/libpython3.5m.dylib

此错误通常发生在同时使用Anaconda配置了Python的其它环境,最简单的解决方法是指定Python版本:

mkvirtualenv -p /usr/bin/python xxxx

# homebrew默认安装的是最新版本的python,如当前brew install python3会安装3.6版本,但由于3.5显然拥有更多的库可以使用,可参照:
brew tap zoidbergwill/python
brew install python35
mkvirtualenv --python=/usr/local/Cellar/python35/3.5.2/bin/python3.5 env

12.setup.py: Not using bundled FreeTDS
这一错同样出现在Mac上,安装pymssql需依赖FreeTDS,按照pymssql官方文档的提示仅需执行brew install freetds,但安装时却会出现错误,解决方法是:

brew unlink freetds
brew install homebrew/versions/freetds091
pip install pymssql

13.
django.db.utils.OperationalError: (1366, “Incorrect string value
出现以上错误请记得将数据库的字符集修改为utf8,Collation修改为utf8_general_ci
MySQL Strict Mode is not set for database connection ‘default’
出现以上错误在DATABASES配置(settings.py)中添加:

'OPTIONS': {
    'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},

14.(1146, “Table ‘***.****’ doesn’t exist”)
a. 删除对应的表格(如果有数据请确保备份数据)
b. 在models.py中注释相关model
c. 执行如下命令

makemigrations
migrate --fake

d. 在models.py中取消相关model注释
e. 执行如下命令

makemigrations
migrate

15.PyCharm激活

网上的激活码基本都已失效,PyCharm确实比较贵,有条件地请支持正版,想体验付费版可以通过在VPS上运行如下代码获取License Server:

wget http://home.ustc.edu.cn/~mmmwhy/jetbrain.sh &amp;amp;&amp;amp; sh ./jetbrain.sh

其它破解方法: http://idea.lanyus.com/

16. Windows下进行pip安装出现类似下面这样的报错

Could not find function xmlCheckVersion in library libxml2

访问http://www.lfd.uci.edu/~gohlke/pythonlibs/找到对应的包(如此处搜索libxml)并完成载先用pip install+下载的文件名安装后再执行安装

17.unicode argument expected, got ‘str’

import io
#Python 2
io.BytesIO()
#Python 3
io.StringIO()
退出移动版