django: delete pevious photo while adding a new photo

Viewed 94

I am developing a user profile where users can add profile picture. Adding the picture is working fine but when I want to add a new photo, old photo doesn't go away. My django version is 3.1 and I have tried django-smartfields but still it is not working. Can anyone help?

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 %}
1 Answers

If your image is being updated in your static/image folder but not in the browser, this is because the browsers cache your static files and they don’t change readily. But there is work around you can use ‘whitenoise’ Follow these steps.

Clear your browser cache to erase already existing cache.

pip3 install whitenoise 

Then add the following to the end of your settings.py

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

Then rerun your server the static files won’t be cached anymore

Related