2

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.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
horbor
  • 609
  • 7
  • 13
  • Did you try `getattr`? `getattr(new_image, 'variable').save(...)` – Paulo Bu Feb 28 '14 at 23:47
  • Wow, thank you, it works this way. Could you explain why it works? In python docs it says getattr only returns a value. Is it django specific? – horbor Mar 01 '14 at 00:19
  • @horbor, no, that's python. You retrieved the value of an attribute called 'variable'. foo.bar = 'hello'; getattr(foo, 'bar'); – Yuji 'Tomita' Tomita Mar 01 '14 at 01:53
  • @Yuji'Tomita'Tomita attribute had no value, so I don't think it returned something that doesn't exist. Still don't get it clearly. – horbor Mar 01 '14 at 08:01
  • This is because of FileField magic. `img_big` is sort of a handle that allows you to get/set this value. When you get you see it is empty, but it allows you to set it. Read about python descriptors :). – pajton Mar 01 '14 at 11:23
  • Thanks, @pajton, for the explanation, great thanks to Paulo Bu and to all of you. I will read more about descriptors in python. – horbor Mar 01 '14 at 22:18

1 Answers1

0

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

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

Thanks, it works!

horbor
  • 609
  • 7
  • 13