Django中使用object.create无法插入图片的技术问题
问题描述
尝试通过object.create将图片插入数据库时,图片始终无法成功插入,但其他数据均可正常插入。经测试,图片已成功生成且可正确加载为JPG格式,但目前只能通过手动指定路径的方式插入图片,希望实现图片的自动插入。
尝试的无效插入代码
stringRegisto = RegistoString.objects.create(string=string_registro, rostosDetectados=frame_io, ecra=estacao_trabalho.owner.photo)
可行的路径插入方式
stringRegisto = RegistoString.objects.create(string=string_registro, rostosDetectados="/rostos/frame_io.jpg", ecra=estacao_trabalho.owner.photo)
Views.py 相关代码
def run_recognition(self, request, frame): print("Executando reconhecimento facial...") rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # 定位帧中的人脸位置 face_locations = face_recognition.face_locations(rgb_frame) # 提取人脸特征 face_encodings = face_recognition.face_encodings(rgb_frame, face_locations) face_names = [] last_face_names = request.session.get('last_face_names', []) _, frame_encoded = cv2.imencode('.jpg', frame) cv2.imwrite('frames/frame_io.jpg', frame) frame_io = ContentFile(frame_encoded.tobytes()) if len(face_encodings) >= 2: # 如果帧中存在两张及以上人脸 self.no_face_count = 0 print("Dois rostos na imagem.") face_names = [] for face_encoding in face_encodings: matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding) name = "Unknown" if True in matches: first_match_index = matches.index(True) name = self.known_face_names[first_match_index] face_names.append(name) estacao_trabalho = EstacaoTrabalho.objects.get(uuid=self.uuid) # 按字母顺序排序姓名 face_names.sort() print("Rostos reconhecidos:", ", ".join(face_names)) estacao_owner_name = estacao_trabalho.owner.name # 检查识别到的人脸是否有变化 if last_face_names == face_names: print("Rostos reconhecidos permanecem os mesmos, não criando registro.") else: # 检查EstacaoTrabalho的所有者姓名是否与识别到的人脸不同 if estacao_trabalho.owner: # 检查工作站是否有所有者 # 如果有所有者,将所有者姓名赋值给estacao_owner_name变量 print("Owner da estação de trabalho:", estacao_trabalho.owner.name) estacao_owner_name = estacao_trabalho.owner.name else: print("Estação de trabalho sem proprietário.") # 如果没有所有者,将空字符串赋值给estacao_owner_name变量 estacao_owner_name = "" string_registro = f"{', '.join(face_names)} estão a visualizar a tela de {estacao_owner_name} na estacao {estacao_trabalho.name}" if not frame_io: raise ValueError("Nenhuma imagem fornecida") stringRegisto = RegistoString.objects.create(string=string_registro, rostosDetectados="/rostos/frame_io.jpg", ecra=estacao_trabalho.owner.photo) stringRegisto.save() print("Registro de string criado:", string_registro) request.session['last_face_names'] = face_names
Models 代码
class RegistoString(models.Model): #Tabela RegistosString string = models.CharField(max_length=100, null=True) rostosDetectados = models.ImageField(upload_to='rostos/',null=True) ecra = models.ImageField(upload_to='ecra/',null=True) def __str__(self): return self.string
解决方法
问题出在ContentFile没有指定文件名,Django的ImageField需要明确的文件名才能正确存储文件。
- 修改
frame_io的创建代码,添加文件名参数,同时移除不必要的本地文件写入操作:
_, frame_encoded = cv2.imencode('.jpg', frame) # 移除本地文件写入,无需保存到本地 # cv2.imwrite('frames/frame_io.jpg', frame) frame_io = ContentFile(frame_encoded.tobytes(), name='frame_io.jpg')
- 在创建
RegistoString对象时直接传入frame_io:
stringRegisto = RegistoString.objects.create( string=string_registro, rostosDetectados=frame_io, ecra=estacao_trabalho.owner.photo )
这样Django就能自动将图片保存到rostos/目录下,并正确关联到RegistoString对象中。
内容的提问来源于stack exchange,提问作者André Pimentel
相关产品推荐
相关产品推荐

