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})

七,启动项目

相关推荐
金銀銅鐵7 分钟前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf24 分钟前
Python 模块与包的导入导出
前端·后端·python
ice8130331811 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
夜微凉41 小时前
三、Spring
java·后端·spring
copyer_xyf1 小时前
Python venv 虚拟环境
前端·后端·python
林爷万福2 小时前
GitHub 开源光谱数据处理项目推荐
python·光纤光谱仪
copyer_xyf2 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python
Full Stack Developme2 小时前
Spring Bean 依赖注入
python·spring·log4j
yuhuofei20212 小时前
【Python入门】Python中的元组tuple
python
Full Stack Developme3 小时前
Spring AOP 与 AspectJ
java·后端·spring