Issue
I have a model in models.py; like this:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='static/images/account/avatar', default='/static/images/default-avatar.png')
bio = models.CharField(max_length=300, blank=True, null=True)
def __str__(self):
return '@' + self.user.username
in views.py i want to check if a filed (i mean avatar) from Profile model has changed or not in views.py:
def editProfile(request):
user = request.user.profile
form = AuthorForm(instance=user)
if request.method == 'POST':
if ...:
os.remove(request.user.profile.avatar.path)
form = AuthorForm(request.POST, request.FILES, instance=user)
if form.is_valid():
form.save()
return redirect('dashboard')
context = {'form': form}
return render(request, 'account/edit.html', context)
In fact, I want the default image (or any other photo) not to be deleted if the user does not change the avatar field.
Solution
The fields that change are listed in the .changed_data
attribute [Django-doc]. You thus can check if the avatar has changed with:
if 'avatar' in form.changed_data:
os.remove(request.user.profile.avatar.path)
Answered By - Willem Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.