django:在添加新照片的同时删除pevious照片



我正在开发一个用户配置文件,用户可以在其中添加配置文件图片。添加图片可以正常工作,但当我想添加新照片时,旧照片不会消失。我的django版本是3.1,我尝试过django smartfields,但仍然不起作用。有人能帮忙吗?

views.py

from smartfields import fields
class Profile_Pic(models.Model):
user = models.ForeignKey(User, default='', null=False, on_delete=models.CASCADE, related_name='userPic')
profile_pic = fields.ImageField(upload_to='media', default='admin_car/static/images/img_avatar.png', blank=True)

class Meta:
db_table = 'Profile_Pic'

user_image.html

{% extends 'datas/base.html' %}
{% block content %}
{% load static %}
<h1 class="text-center" style="color: white">Add Profile Picture</h1>
<br><br>

<div class= "col-md-6.offset-md-3">

<form method="POST" enctype="multipart/form-data">
{% csrf_token %}

{% if form.errors %}
<div class="alert alert-warning alert-dismissable" role="alert">
<button class="close" data-dismiss="alert">
<small><sup>x</sup></small>
</button>
<p>Data Error, Please Check Again.....</p>
{% for field in form %}
{% if field.errors %}
{{ field.errors }}
{% endif %}
{% endfor %}
</div>

{% endif %}

{{ form.as_p }}

<input type="submit" value="Save" class="btn btn-primary">

</form>

</div>
{% endblock %}

如果您的图像在static/image文件夹中更新,而不是在浏览器中更新,这是因为浏览器会缓存您的静态文件,它们不容易更改。但你可以使用"whiteoise"按照以下步骤操作。

清除浏览器缓存以擦除已存在的缓存。

pip3 install whitenoise 

然后将以下内容添加到您的设置末尾。py

if DEBUG:
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
] + MIDDLEWARE
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
] + INSTALLED_APPS

然后重新运行服务器,静态文件将不再缓存

最新更新