开发者

Save generic images from XML nodes

开发者 https://www.devze.com 2023-01-07 15:53 出处:网络
I\'m trying to update my records using XML...so far the first part of the task is done....what I\'m wondering is how to get my images onto the saved object (I\'m using imagekit for the image handl开发

I'm trying to update my records using XML...so far the first part of the task is done....what I'm wondering is how to get my images onto the saved object (I'm using imagekit for the image handl开发者_如何学JAVAing BTW). My models look like this:

class Photo(ImageModel):
    name = models.CharField(max_length=100)
    original_image = models.ImageField(upload_to='photos')
    num_views = models.PositiveIntegerField(editable=False, default=0)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    class IKOptions:
        spec_module = 'my_app.specs'
        cache_dir = 'photos'
        image_field = 'original_image'
        save_count_as = 'num_views'

class Room(models.Model):
    ...
    images = generic.GenericRelation('Photo', blank=True, null=True)
    ...

The XML that I'm using for this is as below:

<room>
    <sq_ft>...</sq_ft>
    <size>...</size>
    <bedrooms>...</bedrooms>
    <images>
        <image>photos/IMG_3406.JPG</image>
        <image>photos/IMG_3416.JPG</image>
        <image>photos/IMG_3409.JPG</image>
    </images>
</room>

My question is how to get the images for a given room when looping through the XML file and save them against that record.

UPDATE 1 I've tried this bit so far:

if room.getElementsByTagName('image'):
    photo = ""
    for v in room.getElementsByTagName('images'):
        photo = v.childNodes[0].nodeValue
        room_photo = Photo.objects.create(content_object = room, 
            object_id = room.id, original_image = photo)

This does save the photo (somewhat), but then the original_image field is always blank, meaning that I'm doing something wrong in the above piece of code. Any ideas?


Have you taken a look at xml_models? Not sure if it's exactly right for you because I'm not 100% sure of what you're asking. However, it does take care of relationships with models that use XML very smoothly, so may solve your problem incidentally :-)

I think xml_models will work for you. Let me know!


Figured this out as the solution finally:

imagelist = room.getElementsByTagName('image')
if imagelist:
    for child in imagelist:
        photo = child.childNodes[0].nodeValue
        room_photo = Photo.objects.create(content_object = room, 
                    object_id = room.id, original_image = photo)

Thought this might help someone with a similar problem later on.

0

精彩评论

暂无评论...
验证码 换一张
取 消