Django筆記(Django上傳頭像)
阿新 • • 發佈:2019-01-09
1.寫一個對應的model (TmageField)
例項:
from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class MyUser(AbstractUser): phone = models.CharField( max_length=13, verbose_name="手機號", unique=True ) icon = models.ImageField( upload_to="icons", null= True, )
2.前端:
注意:from表單上傳檔案需要新增 enctype='multipart/form-data' method=‘post’ 屬性 至少要有一個型別是file的input標籤
例項:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> img{ border-radius: 50%; width: 100px; height: 100px; } </style> </head> <body> 歡迎{{ u_name }} <img src="{{ icon }}" alt=""> <form action="/dj05app/update" enctype="multipart/form-data" method="post"> <input type="file" name="u_icon"> <input type="submit" value="上傳頭像"> </form> </body> </html>
3.後端
1.在static資料夾下建立一個uploadefiles的資料夾,用來儲存接收上傳的檔案
2.在settings.py中配置
# 設定檔案儲存路徑
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/uploads')
# 配置查詢靜態檔案路徑
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
3.生成圖片的隨機名稱,需要在專案APP下建立一個my_utils.py ,把隨機數的工具函式寫在裡面
import uuid import hashlib def get_random_str(): #獲取uuid的隨機數 uuid_val = uuid.uuid4() #獲取uuid的隨機數字符串 uuid_str = str(uuid_val).encode('utf-8') #獲取md5例項 md5 = hashlib.md5() #拿取uuid的md5摘要 md5.update(uuid_str) #返回固定長度的字串 return md5.hexdigest()
4.拿檔案,給物件賦值
@login_required(login_url="/dj05app/my_login")
def update_msg(req):
user = req.user
print(user.icon)
if req.method == "GET":
data = {
'u_name': user.username
#拿頭像檔案路徑
'icon': '/static/uploads/icons/hehe.jpg'
}
return render(req, 'person.html', data)
else:
#拿檔案資料
icon = req.FILES['u_icon']
#獲取圖片的隨機名
file_name = 'icons/' + get_rabdom_str() + '.jpg'
#拼接一個自己的檔案路徑
image_path = os.path.join(settings.MEDIA_ROOT, file_name)
#開啟拼接的檔案路徑
with open(image_path, 'wb')as fp:
#遍歷圖片的塊資料(切塊的傳圖片)
for i in icon.chunks():
#將圖片資料寫入自己的那個檔案
fp.write(i)
#拼接返回資料
data = {
'u_name': user.username
#拿頭像檔案路徑
'icon': '/static/uploads/' + file_name
}
print(user.icon)
return render(req, 'person.html', data)