質問

I am new to Django and already have read and tried everything that came into my mind.

I have a Model-based Form. The model includes 3 FileField fields:

img_big = models.FileField(upload_to='images/%Y/%m/b',max_length=100)
img_med = models.FileField(upload_to='images/%Y/%m/m',max_length=100)   
img_sml = models.FileField(upload_to='images/%Y/%m/s',max_length=100)

In my code, I want to iterate through these fields and save a generated file into each field. 'img' is our file, filename is a filename. So, here is what works:

new_image.img_big.save(filename, img)

but I need to have a variable with field name instead of img_big, for example:

new_image.variable.save(filename, img)
or 
new_image.'test_'+filename.save(filename, img)

I tried to play with setattr(), but I cannot or don't know how to set file name using it, probably it's not possible in this case.

new_image.__dict__['fieldname'].save(filename, img)

doesn't work either.

役に立ちましたか?

解決

As Paulo Bu noticed, the right solution is simple, use getattr():

getattr(new_image, 'variable').save(...)

Thanks, it works!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top