0

I have a view for an account profile. I'd like the user to be able to edit an image once they've added one. I have the edit code. Once a user edits an image, it adds that image to the db, but doesn't remove the previous image.

So the question is, how do I do the following:

Check to see if an image exists If it does delete it Add the new image

My view is located below, any suggestions are welcome.

@login_required def profile_img_edit(request, username, id): '''Edit a Profile Image''' messages.success(request, "Your changes were saved!") user = get_object_or_404(User, username=username) if request.user != user: return permission_denied(request) profile_img = get_object_or_404(ProfileImage, user=user, id=id) if request.method == 'POST': form = Profile_ImageEditForm(request.POST, request.FILES, instance=profile_img) if form.is_valid(): form.save() return HttpResponseRedirect( reverse('profile_img', kwargs={ 'username': request.user.username, 'id': profile_img.id})) else: form = Profile_ImageEditForm() return render_to_response('accounts/profile_img_edit.html', { 'form':form, 'object':profile_img }, context_instance=RequestContext(request)) 
2
  • Are you actually storing the images in the database, or are you storing paths to the image files? ImageField stores paths. Also, you could call this a feature, "non-destructive editing". It's all the rage. :) Commented Jul 29, 2011 at 14:55
  • The idea is to actually keep the image n the server, just in case. But to remove the record from the db. Commented Jul 30, 2011 at 14:42

1 Answer 1

1

Instead of adding a new profile_img instance just update the old one in the db:

ProfileImg.objects.filter(user=user).update(img_path='new_image_path') 

Not sure if you already are but you should be connecting your ProfileImg model to your User model using ForeignKey .

Sign up to request clarification or add additional context in comments.

3 Comments

I did mean from the database. Removing the record of it. It can stay on the server, that's fine. As long as the record of it is removed from the db.
nice, thats actually much simpler! just use the update method in your query (revised answer to reflect)
@Dave Merwin just added a new answer, let me know if that works for you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.