我要上传图片,但是它没有显示在媒体文件夹中。
这是HTML模板
<form class="form" action="/profile/edit/{{user.id}}" method="post" enctype="multipart/form-data" style="padding-top:20px;">
{% csrf_token %}
<input type="file" class="btn " name="pro_pic" accept=".png, .jpg, .jpeg">
<button type="submit" class="btn text-success" name="pr_pic" id="pic_submit"><i class="fas fa-check"></i> Submit</button>
</form>
Models.py
class UserDetails(models.Model):
user_id = models.IntegerField(unique=True)
bio = models.TextField(null = True)
profession = models.CharField(max_length = 100, null = True)
city = models.CharField(max_length = 100, null = True)
country = models.CharField(max_length = 100, null = True)
img = models.ImageField(upload_to='pic_user', null = True)
views.py
def edit (request, id = '') :
if request.user.is_authenticated == True :
if request.method == 'POST' :
# MyModel.objects.filter(pk=some_value).update(field1='some value')
if request.POST.get('pr_pic') == '' :
post_image = request.FILES['pro_pic']
# pic = UserDetails.objects.filter(user_id = id).update(img = post_image)
# UserDetails.objects.filter(user_id = id).update(img = post_image)
pic = UserDetails.objects.filter(user_id = id)
pic.img = post_image
pic.save()
无论何时创建用户,他的user_id都会在另一个表(UserDetails模型)中更新,并且字段为空。
但是在HTML ive中,有一个选项可以稍后上传图像(该ive在HTML中显示)。
我认为我的views.py错误,请帮助我更正
答案 0 :(得分:0)
尝试:
import uuid
from PIL import Image
format_image, img_str = request.FILES['pro_pic'].split(';base64,')
file_content = ContentFile(base64.b64decode(img_str))
unique_filename = str(uuid.uuid4())
pic.img.save(unique_filename, file_content)
file_url = settings.MEDIA_FILES + '/tmp/' + unique_filename
# convert image into JPEG format and save
img = Image.open(file_url)
img.save(file_url, format='jpeg', optimize=True, quality=85)