我有两个模型 - 一个包含标准ImageField
,另一个是ImageField
的内联形式。
普通标准ImageField
在页面上呈现选项"清除[ing]" inlineformset
ImageFields
使用可选"删除"复选框。
“清除”或“删除”将从用户的配置文件中删除图像,但实际的图像文件将保留在存储中,以及图像的URL。
我试图删除所有与图像的关联,一旦用户通过"清除"或"删除"图像。
我发现FieldFile.delete我认为只需要我在实例上调用.delete()
,但我不确定如何有条件地检查用户是否使用"删除&来更新表单#34;框或"清除"盒子打勾。
以下是包含图像字段的两个模型:
class Profile(models.Model):
profile_photo = models.ImageField(
upload_to=profile_photo_upload_loc,
null=True,
blank=True,
verbose_name='Profile Image',
)
class CredentialImage(models.Model):
profile = models.ForeignKey(Profile, default=None,
related_name='credentialimage')
image = models.ImageField(
upload_to=credential_photo_upload_loc,
null=True,
verbose_name='Image Credentials',
)
ModelForms:
class ProfileUpdateForm(ModelForm):
class Meta:
model = Profile
fields = [
"profile_photo",
]
class CredentialImageForm(ModelForm):
image = ImageField(required=False, widget=FileInput)
class Meta:
model = CredentialImage
fields = ['image', ]
CredentialImageFormSet = inlineformset_factory(Profile,
CredentialImage, fields=('image', ), extra=2)
观点:
class ProfileUpdateView(LoginRequiredMixin, UpdateView):
form_class = ProfileUpdateForm
def get_context_data(self, **kwargs):
data = super(ProfileUpdateView, self).get_context_data(**kwargs)
if self.request.POST:
data['credential_image'] = CredentialImageFormSet(self.request.POST, self.request.FILES, instance=self.object)
else:
data['credential_image'] = CredentialImageFormSet(instance=self.object)
return data
def get_object(self, *args, **kwargs):
user_profile = self.kwargs.get('username')
obj = get_object_or_404(Profile, user__username=user_profile)
return obj
def form_valid(self, form):
data = self.get_context_data()
formset = data['credential_image']
if formset.is_valid():
self.object = form.save()
formset.instance = self.object
formset.save()
return redirect(self.object.get_absolute_url())
else:
print("WTF")
instance = form.save(commit=False)
instance.user = self.request.user
return super(ProfileUpdateView, self).form_valid(form)
我的观点是各种各样的混乱,但它似乎工作。现在希望在更新时从存储中完全删除图像文件。
答案 0 :(得分:0)
使用Django清理:
pip install django-cleanup
settings.py
INSTALLED_APPS = (
...
'django_cleanup', # should go after your apps
...
)