The following code uses a form to save a new user avatar picture, however I cannot get this to delete the delete the old avatar and update with the new on. I’ve tried many different code variations.
Could someone point me in the correct direction. An explanation on why this is happening and brief example would be very helpful. All help is greatly appreciated.
model
class Profile(models.Model):
user = models.ForeignKey('auth.User')
avatar = Image..................
view
@login_required
def profile(request, pk):
profile = Profile.objects.get(user=pk)
pf = ProfileForm(request.POST, request.FILES, instance=profile)
if request.method =="POST":
if pf.is_valid():
profile.avatar.delete() #doesn't work
pf.save()
return render_to_response('template.html', {
'profile': profile,
'pf':pf
}, context_instance=RequestContext(request))
template
<form enctype="multipart/form-data" action="" method="POST"> {% csrf_token %}
{{ pf }}
<input type="submit" value="Submit" id="submit" />
</form>
Relationships act like the
objectsattribute.MyModel.objects.delete()wouldn’t work either. You need to do something likeprofile.avatar.all().delete()UPDATE: The above applies to many-to-many relationships.
delete()can be accessed directly off a foreign key.When deleting a foreign key, though, Django removes the associated database row and nullifies the foreign key’s
pk/idattribute, but it does not clear out the data for the foreign key immediately. You could technically, do something like:And, you would end up with the same object, only with a different primary key.