I created a method that generates a new class and adds some methods to the class, but there is a strange error, and I'm not sure what happens:
def make_image_form(image_fields):
''' Takes a list of image_fields to generate images '''
images = SortedDict()
for image_name in image_fields:
images[image_name] = forms.ImageField(required=False)
new_form = type('ListingImagesForm2', (forms.BaseForm,), {'base_fields' : images})
for image_name in image_fields:
print "image name is: ", image_name
setattr(new_form, 'clean_' + image_name, lambda self: self._clean_photo(image_name))
setattr(new_form, '_clean_photo', _clean_photo)
return new_form
This is my method that takes a list of image_fields (I'm building a site in Django) and it creates a whole bunch of ImageField fields and creates a ListingImagesForm2 class and assigns image fields to the class.
The problem is the creation of methods and, more specifically, the content of the method.
In the loop:
for image_name in image_fields:
print "image name is: ", image_name
setattr(new_form, 'clean_' + image_name, lambda self: self._clean_photo(image_name))
Method signatures are created correctly (for example, clean_pic_1, clean_pic_2 ...), but I think that there is a problem in the lambda expression, since the _clean_photo method is always called with the same image name (which turns out to be the last image name in the image_fields list) .
- (), -?
- _clean_photo _ for?