0%

django

database

settings.py

1
2
3
4
5
6
7
8
9
10
11
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'django_mysql', # 数据库名
'USER': 'root', # 账号
'PASSWORD': 'root', # 密码
'HOST': '127.0.0.1', # HOST
'POST': 3306, # 端口

}
}

如果报错
ImproperlyConfigured: mysqlclient 1.3.13 or newer is required

pip install mysqlclient

django ImageField 存储图片

ref

matplotlib 图片存储 ImageField

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from django.core.files.images import ImageFile
from io import BytesIO
import matplotlib.pyplot as plt

# plt 图表
plt.figure(figsize=(12, 6))
plt.title('Actual vs predicted')
plt.scatter(x, y)
plt.plot(x, y_pred, color='black')

# 转换图片
sio = BytesIO()
plt.savefig(sio, format='png')
plt.close() # 记得关闭,不然画出来的图是重复的
img = ImageFile(sio, name="{}_train.png".format(name))

# django model 存储
class model(models.Model):
img_field = models.ImageField(upload_to='img')

m = model(img_field=img)
m.save()

# settings.py
MEDIA_ROOT = 'media/'

# urls.py
from django.urls import path, include, re_path
from django.conf import settings

from django.views.static import serve

urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'media/(?P<path>.*)$',serve,{'document_root':settings.MEDIA_ROOT}),
]

根据项目依赖生成 requirements.txt

安装 pipreqs

pip install pipreqs

在当前目录生成

pipreqs . –encoding=utf8 –force

注意 –encoding=utf8 为使用utf8编码,不然可能会报UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xae in position 406: illegal multibyte sequence 的错误。

–force 强制执行,当 生成目录下的requirements.txt存在时覆盖。