在添加新图像之前如何检查图像是否存在并删除它 - Django
我有一个帐户配置文件的视图。我希望用户在添加图像后能够编辑图像。我有编辑代码。一旦用户编辑图像,它就会将该图像添加到数据库中,但不会删除以前的图像。
所以问题是,我该如何执行以下操作:
检查图像是否存在 如果确实删除它 添加新图像
我的视图位于下面,欢迎任何建议。
@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))
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))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要添加新的 profile_img 实例,只需更新数据库中的旧实例:
不确定您是否已经是,但您应该使用foreignkey将您的 ProfileImg 模型连接到您的 User 模型。
Instead of adding a new profile_img instance just update the old one in the db:
Not sure if you already are but you should be connecting your ProfileImg model to your User model using ForeignKey .