Django 管理员:为图像或文件字段添加“移除文件”字段
我在网上找了一种简单的方法,让用户可以在管理后台清空他们设置的图片或文件字段。
我发现了这个链接:http://www.djangosnippets.org/snippets/894/。
让我觉得特别有意思的是,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
我尝试把这个代码用在我自己的表单中,基本上是把它加到了我的 admin.py
文件里,这个文件里已经有一个 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
但是当我运行它的时候,出现了一个错误:
调用 Python 对象时超出了最大递归深度
错误出现在这一行:
object = super(self.__class__, self).save(*args, **kwargs)
仔细想想,这个错误的原因很明显,就是它一直在无限调用自己,导致了错误。我的问题是,我不知道应该怎么正确地做这件事。
如果有建议的话,请告诉我。
根据要求提供的额外信息:
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
2 个回答
0
我在我的电脑上测试过了,结果是可以正常工作的 :-) 。我用的就是你那段代码。
问题应该出在这段代码之外。
请发一下你是怎么调用/保存表单的,还有模型 Blah 的声明。
你有没有重写模型 Blah 的保存方法?
3
千万不要使用 super(self.__class__, self)
!我们来看一个例子:
class A(object):
def m(self):
super(self.__class__, self).m()
class B(A): pass
B().m()
这个例子会出现同样的错误:
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
的实例调用 A.m
方法,所以 self.__class__
是 B
。而 super(self.__class__, self).m
实际上指向的还是 A.m
方法,这样就导致 A.m
自己调用自己,而不是调用父类的方法。这就造成了无限递归。