Django无法将float转换为Decimal。首先将浮点数转换为字符串

时间:2013-04-18 10:50:34

标签: django

我有一个模型可以在您上传图片时自动重新调整图像尺寸并保存原件。

问题是,当我在管理面板上保存图像时,我收到此错误

无法将float转换为Decimal。首先将浮点数转换为字符串

File "C:\o\mysite\fruit\models.py" in save
 61.         super(Pic, self).save(*args, **kwargs)
 File "C:\Python26\lib\decimal.py" in __new__
  652.                             "First convert the float to a string")

Exception Type: TypeError at /admin/fruit/pic/add/
Exception Value: Cannot convert float to Decimal.  First convert the float to a string

我无法理解为什么会出现此错误

我的models.py

class Pic(models.Model):
    user = models.ForeignKey(User)
    image = models.ImageField(
        upload_to="image",
        blank=True
        )
    descrip = models.TextField()
    ratio = models.DecimalField(decimal_places=5,max_digits=10,default=0)

    def __unicode__(self):
        return self.descrip

    def original(self):
        width = self.image.width / float(self.ratio)
        height = self.image.height / float(self.ratio)

        result = "<img src='/media/{0}' height='{1}' width='{2}'>".format(
            self.image, height, width)

    return result

    def save(self, *args, **kwargs):       
        pw = self.image.width
        ph = self.image.height
        mw = 200
        mh = 200

        self.ratio = getWH(pw, ph, mw, mh, 'r')

        super(Pic, self).save(*args, **kwargs)

        if (pw > mw) or (ph > mh):
            filename = str(self.image.path)
            imageObj = img.open(filename)

            ratio = 1

            if (pw > mw):
                ratio = mw / float(pw)
                pw = mw
                ph = int(math.floor(float(ph)* ratio))
            if ( ph > mh):
                ratio = ratio * ( mh /float(ph))
                ph = mh
                pw = int(math.floor(float(ph)* ratio))

            width = getWH(pw, ph, mw, mh, 'w')
            height = getWH(pw, ph, mw, mh, 'h')

            imageObj = imageObj.resize((width, height),img.ANTIALIAS)
            imageObj.save(filename)



def getWH(pw, ph, mw, mh, result):
    ratio = 1

    if (pw > mw):
        ratio = mw / float(pw)
        pw = mw
        ph = int(math.floor(float(ph)* ratio))
    if ( ph > mh):
        ratio = ratio * ( mh /float(ph))
        ph = mh
        pw = int(math.floor(float(ph)* ratio))

    if result == 'w':
        return pw
    elif result == 'h':
        return ph
    else:
        return ratio

2 个答案:

答案 0 :(得分:5)

使用Python 2.7 +:

from decimal import Decimal
Decimal.from_float(234.234)

https://docs.python.org/2/library/decimal.html#decimal.Decimal.from_float

答案 1 :(得分:4)

从官方文档9.4.8. Decimal FAQ

开始
  

Q值。为什么模块中不包含float_to_decimal()例程?

     

一个。关于混合二进制是否合适存在一些问题   和十进制浮点。此外,它的使用需要一些小心避免   与二进制浮点相关的表示问题:

顺便说一句,你可以在给定的链接中找到答案:

def float_to_decimal(f):
    "Convert a floating point number to a Decimal with no loss of information"
    n, d = f.as_integer_ratio()
    numerator, denominator = Decimal(n), Decimal(d)
    ctx = Context(prec=60)
    result = ctx.divide(numerator, denominator)
    while ctx.flags[Inexact]:
        ctx.flags[Inexact] = False
        ctx.prec *= 2
        result = ctx.divide(numerator, denominator)
    return result

此功能也已包含在python 2.7中。