本文实例为大家分享了django实现上传图片的具体代码,供大家参考,具体内容如下
1.设置存放上传的图片的文件夹
settings.py
1
2
|
media_root = os.path.join(base_dir, 'media' ).replace( '\\', ' / ') media_url = '/media/' |
2.创建图片路径的表结构
models.py
1
2
3
4
|
# 存放图片的表 class avatar(models.model): user = models.charfield(max_length = 100 ) photo = models.imagefield(upload_to = 'photos' , default = 'avatar.jpg' ) |
3.构建并实施迁移文件
1
2
|
python manage.py makemigrations python manage.py migrate |
4.添加路径
urls.py
1
2
3
4
5
6
|
from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path( 'upload/' , views.uploadinfo), ] + static(settings.media_url, document_root = settings.media_root) |
5.写逻辑
在view.py
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# 上传图片 def uploadinfo(request): if request.method = = 'post' : # img = request.files.get('photo') # user = request.files.get('photo').name new_img = models.avatar( photo = request.files.get( 'photo' ), # 拿到图片 user = request.files.get( 'photo' ).name # 拿到图片的名字 ) new_img.save() # 保存图片 return httpresponse( '上传成功!' ) return render(request, 'upload.html' ) |
6.添加html页面
文件夹templates
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<!doctype html> <html lang = "en" > <head> <meta charset = "utf-8" > <title>title< / title> < / head> <body> <form action = "/upload/" method = "post" enctype = "multipart/form-data" > { % csrf_token % } < input name = "photo" type = "file" > <button id = "upload" type = "submit" >上传头像< / button> < / form> < / body> < / html> |
7.效果
运行项目,进入upload查看
上传成功之后
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_45776191/article/details/119885707