1. 测试安装富文本编辑器
1. 准备创建form表单测试表单提交时的编辑器
2. 在创建用户之前必须迁移文件,因此迁移文件
3. form表单依赖templates,因此必须创建并且添加到settings.py
4. 添加完成之后发现无法运行测试服务器,必须修改数据表关联删除,修改之后发现改错了,应该是CASE
5. 修改之后认为应该重新迁移数据,但是遇到系统多达十个报错
富文本编辑器内容编写
Jclass Pos tAdmin (adnin . ModelAdmin) :
list_display = ('title' ,'slug' ,'status' , 'created_ on')
list_filter = ("status",)
search_fields = ['title' ,'content']
prepopulated_fields = {'slug': ('title',) }
summernote_fields = ('content' ,)
参考与引用
https://www.zhihu.com/search?type=content&q=python%20django%20%E5%AF%8C%E6%96%87%E6%9C%AC%E7%BC%96%E8%BE%91%E5%99%A8
https://github.com/summernote/django-summernote
https://www.runoob.com/django/django-template.html
https://www.jianshu.com/p/04e3984eda0b
https://blog.csdn.net/weixin_42238876/article/details/109539056
# CKEDITOR---GitHub
https://github.com/django-ckeditor/django-ckeditor
# office document
https://django-ckeditor.readthedocs.io/en/latest/
# instruction
1. https://dev.to/madhubankhatri/how-to-use-ckeditor-in-django-2igi
2. https://samulinatri.com/blog/django-ckeditor-codesnippet-hightlightjs-youtube/
包准备
# 链接地址
https://www.zhihu.com/search?type=content&q=python%20django%20%E5%AF%8C%E6%96%87%E6%9C%AC%E7%BC%96%E8%BE%91%E5%99%A8
# 编辑器安装命令
pip install django-summernote==0.8.11.6 -i https://pypi.tuna.tsinghua.edu.cn/simple
# 图片上传依赖文件
pip install pillow==8.3.1 -i https://pypi.tuna.tsinghua.edu.cn/simple
# 安装数据库支持
pip install pymysql==1.0.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
创建数据表
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sakila |
| sys |
| world |
+--------------------+
6 rows in set (0.07 sec)
mysql> create database test charset=utf8;
Query OK, 1 row affected, 1 warning (0.01 sec)
mysql> create user tester identified by 'tester123';
Query OK, 0 rows affected (0.05 sec)
mysql> grant all on test.* to 'tester'@'%' with grant option;
Query OK, 0 rows affected (0.02 sec)
settings.py中配置数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'test', #数据库名称
'USER': 'tester', # 链接数据库的用户名
'PASSWORD': 'tester123', # 链接数据库的密码
'HOST': '127.0.0.1', # mysql服务器的域名和ip地址
'PORT': '3306', # mysql的一个端口号,默认是3306
}
}
项目init配置
import pymysql
pymysql.install_as_MySQLdb()
报错解决
(Test) PS C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts> python manage.py createsuperuser
You have 20 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, django_summernote, sessions.
Run 'python manage.py migrate' to apply them.
Traceback (most recent call last):
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute
return self.cursor.execute(query, args)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
result.read()
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
packet.raise_for_error()
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1146, "Table 'test.auth_user' doesn't exist")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts\manage.py", line 22, in <module>
main()
File "C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 100, in handle
default_username = get_default_username(database=database)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\contrib\auth\management\__init__.py", line 141, in get_default_username
auth_app.User._default_manager.db_manager(database).get(
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\models\query.py", line 431, in get
num = len(clone)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\models\query.py", line 262, in __len__
self._fetch_all()
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\models\query.py", line 51, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute
return self.cursor.execute(query, args)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
result.read()
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
packet.raise_for_error()
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
django.db.utils.ProgrammingError: (1146, "Table 'test.auth_user' doesn't exist")
(Test) PS C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts> python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, django_summernote, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying django_summernote.0001_initial... OK
Applying django_summernote.0002_update-help_text... OK
Applying sessions.0001_initial... OK
创建超级管理员
(Test) PS C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts> python manage.py createsuperuser
用户名 (leave blank to use '41999'): tester
电子邮件地址: 419997284@qq.com
Password:
Password (again):
Error: Your passwords didn't match.
Password:
Password (again):
密码跟 用户名 太相似了。
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
(Test) PS C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts>
将apps注册到settings中
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django_summernote',
'django.contrib.staticfiles',
'blog.apps.BlogConfig'
]
添加templates到settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # 可供添加自定义HTML文件,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
系统的十个报错
SystemCheckError: System check identified some issues:
ERRORS:
auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'blog.UserInfo.groups'.
HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'blog.UserInfo.groups'.
auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes with reverse accessor for 'blog.UserInfo.user_permissions'.
HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'blog.UserInfo.user_permissions'.
blog.Article.tags: (fields.E338) The intermediary model 'blog.Article2Tag' has no field 'article'.
blog.Article.tags: (fields.E338) The intermediary model 'blog.Article2Tag' has no field 'tag'.
blog.Article2Tag: (fields.E336) The model is used as an intermediate model by 'blog.Article.tags', but it does not have a foreign key to 'Article' or 'Tag'.
blog.Category.blog: (fields.E312) The to_field 'nid' doesn't exist on the related model 'blog.Blog'.
blog.Tag.blog: (fields.E312) The to_field 'nid' doesn't exist on the related model 'blog.Blog'.
blog.UserInfo.blog: (fields.E312) The to_field 'nid' doesn't exist on the related model 'blog.Blog'.
blog.UserInfo.groups: (fields.E304) Reverse accessor for 'blog.UserInfo.groups' clashes with reverse accessor for 'auth.User.groups'.
HINT: Add or change a related_name argument to the definition for 'blog.UserInfo.groups' or 'auth.User.groups'.
blog.UserInfo.user_permissions: (fields.E304) Reverse accessor for 'blog.UserInfo.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'.
HINT: Add or change a related_name argument to the definition for 'blog.UserInfo.user_permissions' or 'auth.User.user_permissions'.
System check identified 10 issues (0 silenced).
如何解决报错
1. 完成models全部数据表
2. 查询手册,反向解析器冲突的原理
3. 重新梳理表逻辑
遇见报错
WARNINGS:
django_summernote.Attachment: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
HINT: Configure the DEFAULT_AUTO_FIELD setting or the DjangoSummernoteConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
解决方案
1. 参考文档 [https://blog.csdn.net/sunjl_a/article/details/116482203]
2. add another field into settings
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
遇见报错
Operations to perform:
Apply all migrations: admin, auth, contenttypes, django_summernote, sessions
Running migrations:
Applying admin.0001_initial...Traceback (most recent call last):
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 82, in _execute
return self.cursor.execute(sql)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute
return self.cursor.execute(query, args)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
result.read()
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
packet.raise_for_error()
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.OperationalError: (1050, "Table 'django_admin_log' already exists")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts\manage.py", line 22, in <module>
main()
File "C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
post_migrate_state = executor.migrate(
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\operations\models.py", line 92, in database_forwards
schema_editor.create_model(model)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 345, in create_model
self.execute(sql, params or None)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 145, in execute
cursor.execute(sql, params)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 82, in _execute
return self.cursor.execute(sql)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute
return self.cursor.execute(query, args)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\cursors.py", line 148, in execute
result = self._query(query)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\cursors.py", line 310, in _query
conn.query(q)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\connections.py", line 548, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\connections.py", line 775, in _read_query_result
result.read()
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\connections.py", line 1156, in read
first_packet = self.connection._read_packet()
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\connections.py", line 725, in _read_packet
packet.raise_for_error()
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
err.raise_mysql_exception(self._data)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
raise errorclass(errno, errval)
django.db.utils.OperationalError: (1050, "Table 'django_admin_log' already exists")
解决方案
1. 参考文档 [https://blog.csdn.net/m0_37605642/article/details/92812328]
# SQL
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| test |
+--------------------+
2 rows in set (0.01 sec)
mysql> use test;
Database changed
mysql> show tables;
+---------------------+
| Tables_in_test |
+---------------------+
| django_admin_log |
| django_content_type |
| django_migrations |
+---------------------+
3 rows in set (0.00 sec)
mysql> drop table django_admin_log;
Query OK, 0 rows affected (0.03 sec)
mysql>
新的报错
jango.db.utils.OperationalError: (1824, "Failed to open the referenced table 'blog_userinfo'")
1. reference [https://blog.csdn.net/qq_33654685/article/details/88573873]
python manage.py showmigrations
2. 添加migrations 以及__init__
报错及解决
1. raise ValueError("Dependency on app with no migrations: %s" % key[0])
2. reference [https://blog.csdn.net/lezeqe/article/details/85638439]
3. 执行命令 python manage.py makemigrations
安装ckeditor
1. reference
https://segmentfault.com/a/1190000018607948
1. 安装插件
pip install django-ckeditor==6.1.0
2. 遇到的报错
You are trying to add a non-nullable field 'body' to comment without a default; we can't do that
技术总结
1. 准备包,在settings中注册app
2. 在model类中添加 body = RichTextField(),并且迁移文件
3. 将model.class注册到app.admin中
2. 配置文件系统和静态文件查找器以及路径
核心思想:
1. 配置静态文件查找路径
2. 配置静态文件路径
3. 这是一个私有接口,因此没有开发文档
# 文件系统默认配置
# https://docs.djangoproject.com/zh-hans/3.2/ref/settings/#staticfiles-finders
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
# 静态文件的存放路径
# https://docs.djangoproject.com/zh-hans/3.2/ref/settings/#std:setting-STATICFILES_DIRS
# file path style : "C:/Users/user/mysite/extra_static_content"
STATICFILES_DIRS = [
"whereabouts/",
]
配置日志记录—-收集可能复现的bug
# 日志配置文件
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
# 消息处理引擎,可以定义多个以便处理不同级别信息
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': 'C:/Users/41999/Documents/项目管理/Test/Scripts/whereabouts/blog/django.log', # 注意,你的文件应该有读写权限。
'maxBytes': '100 * 1024 * 1024',
'encoding': 'utf-8',
},
},
# 日志系统入口
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
配置运行时报错
ValueError: Unable to configure handler 'file'
1. 参考文档
1. https://www.cnblogs.com/yebaofang/p/13647899.html
2. https://stackoverflow.com/questions/39101488/valueerror-unable-to-configure-handler-file-errno-2-no-such-file-or-direct#
3. https://www.jianshu.com/p/bd9fcb0812a1
4. 命令行报错
python manage.py checkout
# 处理过程
1. 根据报错找到config配置文件,查看官方文档
[https://docs.python.org/zh-cn/3/library/logging.config.html?highlight=config%20py]
2. 发现指定处理的函数错了,config确实不包含maxBytes
3. 在config.py官方文档中找到包含限定大小参数的函数
[logging.handlers.RotatingFileHandler]
4. 依然报错,仍由config处理maxBytes
5. 查看该处理函数,确实包含maxBytes.
1. 报错
(Test) PS C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts> python manage.py checkout
C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts
Traceback (most recent call last):
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\logging\config.py", line 564, in configure
handler = self.configure_handler(handlers[name])
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\logging\config.py", line 745, in configure_handler
result = factory(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'maxBytes'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts\manage.py", line 22, in <module>
main()
File "C:\Users\41999\Documents\项目管理\Test\Scripts\whereabouts\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\core\management\__init__.py", line 395, in execute
django.setup()
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\__init__.py", line 19, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "C:\Users\41999\Documents\项目管理\Test\lib\site-packages\django\utils\log.py", line 75, in configure_logging
logging_config_func(logging_settings)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\logging\config.py", line 809, in dictConfig
dictConfigClass(config).configure()
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\logging\config.py", line 571, in configure
raise ValueError('Unable to configure handler '
ValueError: Unable to configure handler 'file'
函数结构[logging.handlers.RotatingFileHandler]
class BaseRotatingHandler(logging.FileHandler)
I class RotatingFileHandler(BaseRotatingHandler)
class TimedRotat ingF ileHandler(BaseRotatingHandler)
class WatchedFileHandler(logging.FileHandter)
class SocketHandler(logging.Handler)
class DatagramHandler(SocketHandler)
class SysLogHandler( logging.Handler)
class SMTPHandler(logging.Handler)
class NTEventLogHandler(logging.Handler)
class HTTPHandler(logging.Handler)
class BufferingHandler(logging.Handler)
class MemoryHandler(Buf feringHandler)
C:\Users\41999\Documents\projectmanagement\Test\Scripts\whereabouts
Traceback (most recent call last):
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\logging\config.py", line 564, in configure
handler = self.configure_handler(handlers[name])
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\logging\config.py", line 745, in configure_handler
result = factory(**kwargs)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\logging\handlers.py", line 151, in __init__
if maxBytes > 0:
TypeError: '>' not supported between instances of 'str' and 'int'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\41999\Documents\projectmanagement\Test\Scripts\whereabouts\manage.py", line 22, in <module>
main()
File "C:\Users\41999\Documents\projectmanagement\Test\Scripts\whereabouts\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\41999\Documents\projectmanagement\Test\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\41999\Documents\projectmanagement\Test\lib\site-packages\django\core\management\__init__.py", line 395, in execute
django.setup()
File "C:\Users\41999\Documents\projectmanagement\Test\lib\site-packages\django\__init__.py", line 19, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "C:\Users\41999\Documents\projectmanagement\Test\lib\site-packages\django\utils\log.py", line 75, in configure_logging
logging_config_func(logging_settings)
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\logging\config.py", line 809, in dictConfig
dictConfigClass(config).configure()
File "C:\Users\41999\AppData\Local\Programs\Python\Python39\lib\logging\config.py", line 571, in configure
raise ValueError('Unable to configure handler '
ValueError: Unable to configure handler 'file'
解决方案,放弃配置文件中maxBytes
1. 遗留问题: maxBytes没能写到配置文件中去,功能需求:按24小时间隔生成log
2. 有效参考:https://www.bilibili.com/video/BV1SK4y1K7wm
3. Lib/logging/handlers.py:
[https://docs.python.org/zh-cn/3/library/logging.handlers.html]
4. django官方文档配置
[https://docs.djangoproject.com/zh-hans/3.2/topics/logging/#configuring-logging]
5.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
# 消息处理引擎,可以定义多个以便处理不同级别信息
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'C:/Users/41999/Documents/projectmanagement/Test/Scripts/whereabouts/logs/debug.log', # 注意,你的文件应该有读写权限。
# 'maxBytes': '100 * 1024 * 1024',
'encoding': 'utf-8',
},
},
# 日志系统入口
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
Git远程仓库配置
1. 新建忽略文件
安装simpleui
1. 项目地址:[https://github.com/newpanjing/simpleui]
2. 使用教程 [https://simpleui.72wo.com/docs/simpleui/doc.html]
配置方法
1. 使用git或者GitHub自带的下载功能,将代码完全clone到本地
2. 在文件夹中新建项目下的static
3. settings中配置STATIC_ROOT = os.path.join(BASE_DIR, 'static')
4. 终端执行命令: [python manage.py collectstatic]
3. 登录页面书写
无法加载bootstrap
解决方案
1. settings添加配置 [https://www.jb51.net/article/183668.htm]
STATICFILES_DIRS = [
# "whereabouts/",
os.path.join(BASE_DIR, 'blog', 'static')
]
2. reference https://docs.djangoproject.com/zh-hans/3.2/howto/static-files/
3. reference https://docs.djangoproject.com/zh-hans/3.2/ref/contrib/staticfiles/#django-admin-collectstatic
第二日解决方案
1. 解决思路,template下新建base.h5从中分出一个模板区域,用于外部引用。在登录页面使用标签引用指定内容,然后在登录页面顶端打开外部引入
2. reference [https://www.learncodewithmike.com/2020/03/django-bootstrap.html]
3. bootstrap https://getbootstrap.com/docs/5.1/getting-started/introduction/
解决步骤
新建文件
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<title>Template-Base</title>
</head>
<body>
<h1>Welcome to Blog of Caesar Tylor</h1>
<div>
{% block content%}
{% endblock %}
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js" integrity="sha384-eMNCOe7tC1doHpGoWe/6oMVemdAVTMs2xqW4mwXrXsW0L84Iytr2wi5v2QjrP/xp" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.min.js" integrity="sha384-cn7l7gDp0eyniUwwAZgrzD06kc/tftFf19TOAs2zVinnD/C7E91j9yyk5//jjpt/" crossorigin="anonymous"></script>
-->
</body>
</html>
登录页面改写
<!DOCTYPE html>
{% extends 'base.html' %}
{% load static %}
<html lang="en">
{% block content %}
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-lg-offset-3"> {# 占用六个,右倾 #}
<form> {# action不再定义,基于Ajax提交 #}
<div>
<label for="user">用户名</label>
<input type="text" id="user" class="form-control"> {# ID用于Ajax获取信息 #}
</div>
<div>
<label for="pwd">密码</label>
<input type="password" id="pwd" class="form-control">
</div>
<input type="button" class="btn btn-default login_btn pull-right" value="submit"> {# login_btn用于绑定事件 #}
</form>
</div>
</div>
</div>
</body>
{% endblock %}
</html>
包无法引入
# 报错
Requirement already satisfied: pillow==8.3.1 in c:\users\41999\documents\projectmanagement\test\lib\site-packages (8.3.1)
1. 解决包无法导入
1. pip list
2. python manage.py shell
# import PIL
内存写入时的错误。
1. 错误的引用包 [from io import ByetsIO]
2.
4. 再战logs
解决思路
1. 参考文档
1. [全能型] https://note.qidong.name/2018/11/django-logging/
2. [logging.config---字典架构细节]
https://docs.python.org/zh-cn/3/library/logging.config.html?highlight=config%20py
3. [logging.handlers.---TimedRotatingFileHandler]
https://docs.python.org/zh-cn/3/library/logging.handlers.html
4. [logging---logging-levels]
https://docs.python.org/zh-cn/3/library/logging.html#logging-levels
5. [日志模块的配置]
https://docs.djangoproject.com/zh-hans/3.2/topics/logging/#configuring-logging
6. []
https://django.readthedocs.io/en/stable/topics/logging.html
7. [when字段的参考]
https://zhuanlan.zhihu.com/p/337456603
8. [刘江的个人博客]
https://www.liujiangblog.com/course/python/71
9. [日志分割解决方案]
https://segmentfault.com/a/1190000039354905
2. 出错的原因
1. 忽略了主要的配置信息,将注意力放在函数定义和规则上
2. 没有完全弄懂参照对象的语法规则
3. 教训
1. 通读单个类别的函数定义和规则
2. 配置文件尽量黏贴加注释,避免出错
4. 过程反思
1. 我的解决方案,首先从最后一条报错入手,拆分单个函数定义开始,查找触发异常的条件,用其他编译器截取部分代码
2. 老师的解决方案,从配置文件的格式出发