Django - Model field keeps the same value!
When I assign a value to an variable of a Field object, why when I reload the ModelForm isn't reassigned to default?
File
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)
Field
class CustomImageField(ImageField):
attr_class = CustomFile
def __init__(self, overrided_name, *args, **kwargs):
self.overrided_name = overrided_name
super(CustomImageField, self).__init__(*args, **kwargs)
Model
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
Admin
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)
My problem is that every image I will upload will have the same name, until I restart the server!.. Why the object doesn't change?! In particular the Field object... when I trace it will result the same object .
I've solved it like so:
class CustomFile(ImageFile, FieldFile):
def save(self, name, content, save = True):
if self.field.override_name:
self(CustomFile, self).save(sel开发者_如何学编程f.field.override_name, content, save = save)
self.field.override_name = None
else:
self(CustomFile, self).save(generate_name(self.instance, name), content, save = save)
I'm using Django 1.2.6, Python 2.6 and Windows!
I am just guessing, but isnt this part of code wrong?
form = TestForm
Should not it be creating an instance instead of referencing to class?
form = TestForm()
or same thing here?
attr_class = CustomFile - > attr_class = CustomFile()
精彩评论