8.Django怎样去调用漂亮的HTML前端页面?

本文介绍了Django如何调用HTML前端页面,强调了模板文件的存放位置和实战中的具体步骤,包括在views.py文件中的设置及HTML模板的创建,最终展示了调用效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每篇前言:

由于您没有提供具体的部署环境,我将提供一个基于Python Django框架和HTML/CSS/JS前端的yolov5模型部署示例。如果您的部署环境不同,请根据具体情况进行相应的调整。 1.Django项目中创建一个名为`models.py`的文件,用于加载yolov5模型并进行预测。 ```python import torch import cv2 import numpy as np from django.conf import settings class YOLOv5: def __init__(self): self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') self.model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True).to(self.device) self.model.eval() def predict(self, image_path): img = cv2.imread(image_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) results = self.model([img], size=640) predictions = results.xyxy[0].cpu().numpy().tolist() return predictions ``` 2.Django项目中创建一个名为`views.py`的文件,用于处理用户请求并调用`models.py`中的模型进行预测。 ```python from django.shortcuts import render from django.conf import settings from .models import YOLOv5 import os def index(request): if request.method == 'POST': # 从HTML表单中获取上传的图像文件 image_file = request.FILES.get('image') # 将图像文件保存到本地 image_path = os.path.join(settings.MEDIA_ROOT, image_file.name) with open(image_path, 'wb') as f: f.write(image_file.read()) # 加载yolov5模型并进行预测 model = YOLOv5() predictions = model.predict(image_path) # 将预测结果传递给HTML模板 context = {'predictions': predictions} return render(request, 'result.html', context) else: return render(request, 'index.html') ``` 3.Django项目中创建一个名为`index.html`的HTML模板,用于显示上传图像的表单。 ```html <!DOCTYPE html> <html> <head> <title>Django YOLOv5 Demo</title> </head> <body> <h1>Django YOLOv5 Demo</h1> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="image"> <button type="submit">预测</button> </form> </body> </html> ``` 4.Django项目中创建一个名为`result.html`的HTML模板,用于显示预测结果。 ```html <!DOCTYPE html> <html> <head> <title>Django YOLOv5 Demo</title> </head> <body> <h1>Django YOLOv5 Demo</h1> <table> <thead> <tr> <th>类别</th> <th>置信度</th> <th>左上角坐标</th> <th>右下角坐标</th> </tr> </thead> <tbody> {% for prediction in predictions %} <tr> <td>{{ prediction.5 }}</td> <td>{{ prediction.4 }}</td> <td>{{ prediction.0 }}, {{ prediction.1 }}</td> <td>{{ prediction.2 }}, {{ prediction.3 }}</td> </tr> {% endfor %} </tbody> </table> </body> </html> ``` 5.Django项目中的`settings.py`文件中添加以下配置,指定上传文件的存储路径。 ```python MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ``` 6. 运行Django项目并访问`http://localhost:8000`,上传一张图像并查看预测结果。
评论 193
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孤寒者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值