在上一节中,我们通过Django建立了一个“最小”项目(https://github.com/jiaxiaolei/my_django_project)。
这次,我们基于上一个项目,建立一个分支,利用Django Admin 的特性,建立一个简单的“发票汇总”系统。
参考代码:https://github.com/jiaxiaolei/my_django_project.git
djang_invoice 分支
切换分支:
$ git status
# 位于分支 master
无文件要提交,干净的工作区
# 尚未暂存以备提交的变更:
基于当前分支,建立一个分支 django_invoice
$ git checkout -b django_invoice
切换到一个新分支 'django_invoice'
$ git status
# 位于分支 django_invoice
$ git branch
* django_invoice
master
$ git branch -a
* django_invoice
master
remotes/origin/HEAD -> origin/master
remotes/origin/master
建立一个远程分支:
$ git push origin django_invoice
Total 0 (delta 0), reused 0 (delta 0)
To git@github.com:jiaxiaolei/my_django_project.git
* [new branch] django_invoice -> django_invoice
修改 module.py,建立models.
filename: project_001/app_001/models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length=20)
amount = models.BigIntegerField()
mobile = models.CharField(max_length=11, blank=True)
#amount = models.IntField(default=1, required=True) models.BigIntegerField()
comments = models.CharField(max_length=30, blank=True)
# 如果不重写__str__方法,默认显示` User object`
def __str__(self):
return "%s" % self.name
因为改了model, 需要生产修改并更新table.
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
$ python manage.py makemigrations
Migrations for 'app_001':
app_001/migrations/0001_initial.py
- Create model User
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, app_001, auth, contenttypes, sessions
Running migrations:
Applying app_001.0001_initial... OK
执行python manage.py makemigrations
, 会在migrations 下生成一些.py文件,比如:
filename: app_001/migrations/0003_user_mobile.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-11 12:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_001', '0002_user_comments'),
]
operations = [
migrations.AddField(
model_name='user',
name='mobile',
field=models.CharField(default='', max_length=11),
preserve_default=False,
),
]
module 中新增一个字段(比如 comments, mobile)之后,服务出现错误提示:
File "/root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
File "/root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 886, in execute_sql
raise original_exception
OperationalError: no such column: app_001_user.comments
[11/Aug/2017 11:56:02] "GET /admin/app_001/user/1/change/ HTTP/1.1" 500 136955
[11/Aug/2017 11:57:42] "GET /admin/app_001/user/1/change/ HTTP/1.1" 200 4971
更新table,并对已有数据提供缺省值。
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, app_001, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
(py2.7.13cmdb2.0) [root@uop-test-ad4b7b17-44b1-4657-ab30-8593ece79d7b project_001]# python manage.py makemigrations
You are trying to add a non-nullable field 'comments' to user without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>>
Please enter some code, or 'exit' (with no quotes) to exit.
>>> ''
Migrations for 'app_001':
app_001/migrations/0002_user_comments.py
- Add field comments to user
(py2.7.13cmdb2.0) [root@uop-test-ad4b7b17-44b1-4657-ab30-8593ece79d7b project_001]# python manage.py migrate
Operations to perform:
Apply all migrations: admin, app_001, auth, contenttypes, sessions
Running migrations:
Applying app_001.0002_user_comments... OK
$ python manage.py makemigrations
You are trying to add a non-nullable field 'mobile' to user without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> ''
Migrations for 'app_001':
app_001/migrations/0003_user_mobile.py
- Add field mobile to user
(py2.7.13cmdb2.0) [root@uop-test-ad4b7b17-44b1-4657-ab30-8593ece79d7b project_001]# python manage.py migrate
Operations to perform:
Apply all migrations: admin, app_001, auth, contenttypes, sessions
Running migrations:
Applying app_001.0003_user_mobile... OK
遇到问题及解决方案
问题:
File "/root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages/django/template/defaultfilters.py", line 47, in _dec
args[0] = force_text(args[0])
File "/root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages/django/utils/encoding.py", line 80, in force_text
s = six.text_type(bytes(s), encoding, errors)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
解决:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
问题:
app_config.import_models()
File "/root/.virtualenvs/py2.7.13cmdb2.0/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/root/.pyenv/versions/2.7.13/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/opt/my_django_project/project_001/app_001/models.py", line 7
from __future__ import unicode_literals
SyntaxError: from __future__ imports must occur at the beginning of the file
解决:
换一下顺序:from __future__ import unicode_literals
作为第一个要导入的包出现。
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
- 问题: 在admin中建立了普通用户,却无法登陆
- 解决: 通过系统管理员建立用户的时候,需要勾选“Staff status”, 以便用户可以正常登录系统。
扩展阅读
Admin后台管理模块的使用
http://www.cnblogs.com/alan-babyblog/p/5812010.html
【python】【django】migrate 和makemigrations的差别
http://blog.csdn.net/yang1z1/article/details/52235424
简介:
python manger.py makemigrations
相当于 在该app下建立 migrations目录,并记录下你所有的关于modes.py的改动,比如0001_initial.py, 但是这个改动还没有作用到数据库文件
在此之后执行命令
python manager.py migrate
将该改动作用到数据库文件,比如产生table之类
Django admin 的 list_display 变量统计后台作者发贴总数
http://blog.csdn.net/lmb20056127/article/details/77863492
简介:
一个举例。
对admin进行扩展。