开发者

Django prepopulated_fields like method

Please forgive my naiveté with Django.

I want to create my own method which works much like prepopulated_fields for my custom admin page. Basically, when you put the url of an image in one field, I'd like to populate another field with the name of the image, height and width via javascript.

What would be the be开发者_StackOverflow社区st approach? Just override the change_form.html and include my own JS lib? Write a custom widget?


Using Javascript would be a probable move, if for some reason you want to show the attributes of the image.

See Javascript - Get Image height for an example of doing this.

If there's no need to show it at the form level but to simply populate the usually prefer to do this at the model level, such as

from PIL import Image
import StringIO
import urllib2

class MyModel(models.Model):
    # ... fields 1,2,3 etc, and assuming the url field is called image_url

    def pre_save():
        # obtain attributes of image from url field
        # save it to various fields
        img = urllib2.urlopen(self.image_url).read()
        im = Image.open(StringIO.StringIO(img))
        self.image_width, self.image_height = im.size

    def save(self, *args, **kwargs):
        self.pre_save()
        super(MyModel, self).save(*args, **kwargs)

Good luck!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜