Django之单文件上传(以图片为例)

一,创建项目

初始化,数据迁移,创建superuser,创建app等

二,配置settings.py

1,配置数据库(本作者使用的mysql),以前文章有提到

2,配置静态文件存放路径

STATICFILES_DIRS=[ BASE_DIR / 'static' ]

3,配置媒体文件(即上传的文件)存放路径

复制代码
MEDIA_ROOT = BASE_DIR / 'static/uploads'

三,按照以下文件树创建文件(static和templates下的文件可自定义,但是这两个文件夹名字要和之前配置的相同)

四,编写html

在templates下创建html,文件名自定义,内容可参考如下:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>单文件上传</title>
</head>
<body>
<h2>单文件上传</h2>
<hr>
<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <p>用户名:<input type="text" name="uname"></p>
    <p>头像:<input type="file" name="icon"></p>
    <p><button>上传</button></p>
</form>
</body>
</html>
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% load static %}
<h2>展示详情页</h2>
<hr>
<ul>
    <li>
        上传者:{{ name }}
    </li>
       
</ul>
 文件:<img src="{% static icon %}" alt="" width="300px">
</body>
</html>

五,创建model

python 复制代码
class upload(models.Model):
    name = models.CharField(max_length=30, unique=True)
    icon = models.CharField(max_length=255)

    def __str__(self):
        return self.name + self.icon

然数据迁移,注册model等

六,编写view

在创建的app的文件下的views.py中写函数,内容可参考如下:

python 复制代码
def upload1(request):
    if request.method == 'GET':
        return render(request, 'upload1.html')
    elif request.method == 'POST':
        uname = request.POST.get('uname')
        icon = request.FILES.get('icon')
        icon_name = str(uuid.uuid4())+ icon.name[icon.name.rfind('.'):]
        file_path = os.path.join(settings.MEDIA_ROOT, icon_name)
        with open(file_path,'ab') as fp:
            for part  in icon.chunks():
                    fp.write(part)
                    fp.flush()
        up = upload()
        up.name = uname
        up.icon = 'uploads/' + icon_name
        up.save()
        return render(request, 'detail.html', {'name':uname, 'icon':file_path})

七,启动项目

相关推荐
sg_knight10 小时前
设计模式实战:模板方法模式(Template Method)
python·设计模式·模板方法模式
FreakStudio10 小时前
ESP32居然能当 DNS 服务器用?内含NCSI欺骗和DNS劫持实现
python·单片机·嵌入式·面向对象·并行计算·电子diy
乐观勇敢坚强的老彭11 小时前
2026全国青少年信息素养大赛考纲
python·数学建模
zb2006412011 小时前
CVE-2024-38819:Spring 框架路径遍历 PoC 漏洞复现
java·后端·spring
uzong11 小时前
AI Agent 是什么,如何理解它,未来挑战和思考
人工智能·后端·架构
追逐时光者11 小时前
DotNetGuide突破了10K + Star,一份全面且免费的C#/.NET/.NET Core学习、工作、面试指南知识库!
后端·.net
YMWM_11 小时前
【问题】thor上的cubLas
linux·python·thor
wefly201711 小时前
免安装!m3u8live.cn在线 M3U8 播放器,小白也能快速上手
java·开发语言·python·json·php·m3u8·m3u8在线转换
yuweiade11 小时前
springboot和springframework版本依赖关系
java·spring boot·后端