当我为Field对象的变量赋值时,为什么在重新加载ModelForm时没有重新赋值为默认值?
文件
class CustomFile(ImageFile, FieldFile):
def save(self, name, content, save = True):
if self.field.override_name:
self(CustomFile, self).save(self.field.override_name, content, save = save)
else:
self(CustomFile, self).save(generate_name(self.instance, name), content, save = save)
字段
class CustomImageField(ImageField):
attr_class = CustomFile
def __init__(self, overrided_name, *args, **kwargs):
self.overrided_name = overrided_name
super(CustomImageField, self).__init__(*args, **kwargs)
模型
class Test(models.Model):
email = models.EmailField()
file = CustomImageField()
AdminForm
class TestForm(ModelForm):
def __init__(self, *args, **kwargs):
super(TestForm, self).__init__(*args, **kwargs)
self.old_instance = self.instance
管理
class TestAdmin(Test):
form = TestForm
def save_model(self, request, obj, form, change):
if form.old_instance:
form.old_instance.file.delete(save = True)
form.old_instance.file.field.override_name = form.old_instance.name
obj.save()
admin.site.register(Test, TestAdmin)
我的问题是我上传的每个图片都会有相同的名称,直到我重新启动服务器! 为什么对象不会改变?!特别是Field对象......当我跟踪它时将产生相同的对象。
我已经解决了这个问题:
class CustomFile(ImageFile, FieldFile):
def save(self, name, content, save = True):
if self.field.override_name:
self(CustomFile, self).save(self.field.override_name, content, save = save)
self.field.override_name = None
else:
self(CustomFile, self).save(generate_name(self.instance, name), content, save = save)
我正在使用Django 1.2.6,Python 2.6和Windows!
答案 0 :(得分:1)
我只是在猜测,但这段代码不是错了吗?
form = TestForm
它不应该是创建实例而不是引用类吗?
form = TestForm()
或者同样的事情在这里?
attr_class = CustomFile - > attr_class = CustomFile()