Django管理员:添加& quot;删除文件& quot;图像或文件字段的字段 [英] Django admin: Add a "remove file" field for Image- or FileFields
问题描述
我在Internet上寻找一种轻松地允许用户清空在管理员中设置的imagefield/filefield的方法.
I was hunting around the Internet for a way to easily allow users to blank out imagefield/filefields they have set in the admin.
我发现了这一点: http://www.djangosnippets.org/snippets/894/.
这里真正令我感兴趣的是 rfugger 在评论中发布的代码:
What was really interesting to me here was the code posted in the comment by rfugger:
remove_the_file = forms.BooleanField(required=False)
def save(self, *args, **kwargs):
object = super(self.__class__, self).save(*args, **kwargs)
if self.cleaned_data.get('remove_the_file'):
object.the_file = ''
return object
当我尝试以自己的形式使用它时,我基本上将其添加到了已经有 BlahAdmin
的 admin.py
中.
When I try to use this in my own form I basically added this to my admin.py
which already had a BlahAdmin
.
class BlahModelForm(forms.ModelForm):
class Meta:
model = Blah
remove_img01 = forms.BooleanField(required=False)
def save(self, *args, **kwargs):
object = super(self.__class__, self).save(*args, **kwargs)
if self.cleaned_data.get('remove_img01'):
object.img01 = ''
return object
我运行它时收到错误消息
When I run it I get the error
调用Python对象时超出了最大递归深度
maximum recursion depth exceeded while calling a Python object
在此行:
object = super(self.__class__, self).save(*args, **kwargs)
当我仔细考虑一下时,很明显它只是无限地调用自身而导致错误.我的问题是我不知道应该怎么做.有什么建议吗?
When I think about it for a bit, it seems obvious that it is just infinitely calling itself causing the error. My problem is I can't figure out what is the correct way I should be doing this. Any suggestions?
根据要求提供的其他信息:
Additional information as requested:
blah 的型号:
Model of blah
:
class Blah(models.Model):
blah_name = models.CharField(max_length=25, unique=True)
slug = models.SlugField()
img01 = models.ImageField(upload_to='scenes/%Y/%m', blank=True)
def __unicode__(self):
return self.blah_name
推荐答案
请勿使用 super(self .__ class__,self)
!请尝试以下示例:
Never use super(self.__class__, self)
! Try the following example:
class A(object):
def m(self):
super(self.__class__, self).m()
class B(A): pass
B().m()
它将失败,并显示相同的错误:
It will fail with the same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in m
... repeated a lot of times ...
RuntimeError: maximum recursion depth exceeded while calling a Python object
让我们看看发生了什么.您为 B
实例调用 Am
方法,因此 self .__ class __
是 B
和 super(self.__class __,self).m
指的是同一方法 Am
,因此 Am
会自行调用,而不是调用基类的方法.这导致无限递归.
Let's see what's going on. You call A.m
method for B
instance, so self.__class__
is B
and super(self.__class__, self).m
refers to the same method A.m
, so A.m
calls itself instead of calling the method of base class. This leads to infinite recursion.
这篇关于Django管理员:添加& quot;删除文件& quot;图像或文件字段的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!