如何在Django Model保存方法中处理上传的文件

时间:2014-11-20 07:34:15

标签: python django

在django默认管理面板中,我需要存储从excel文件上传的所有PIN码

为此我开发了两个模型Pincodes和UploadPinFile。

我想从UploadPinFile的保存方法中将所有密码保存到Pincode模型

但它会给我一个错误,如下所示

强制转换为Unicode:需要字符串或缓冲区,找到FieldFile

下面给出了两种模型的定义

class UploadPincode(models.Model):
    added_on = models.DateField(auto_now_add=True)
    pincode_file = models.FileField(
        upload_to="Pincodes/", verbose_name="Pincode Excel file (.xls,xlsx)", blank=False, null=False)

    def save(self):
        book = open_workbook(self.pincode_file)
        for j in range(0, book.nsheets - 1):
            sheet = book.sheet_by_index(j)
            for i in range(sheet.nrows):
                if i != 0:
                    a = sheet.row_values(i)
                    int_pin = int(a[0])
                    Pincode(pincode=str(int_pin)).save()
    def __unicode__(self):
        return str(self.added_on)

class Pincode(models.Model):
    pincode = models.CharField(
        max_length=100, verbose_name=u'available pincode', null=True, blank=True)

    def __unicode__(self):
        return self.pincode

示例Pincode文件包含

712409  YES
713101  YES
713102  YES
713103  YES
713201  YES
713202  YES
713203  YES

1 个答案:

答案 0 :(得分:3)

您只需为流程创建一个def。它将从save()方法内部调用...

您只需遵循以下代码:

class UploadPincode(models.Model):
    added_on = models.DateField(auto_now_add=True)
    pincode_file = models.FileField(
        upload_to="Pincodes/", verbose_name="Pincode Excel file (.xls,xlsx)", blank=False, null=False)

    def save(self):
        print "Before Save #######"

        super(UploadPincode, self).save()
        print " Save #######"

        pincode_process(self.pincode_file.url)


    def __unicode__(self):
        return str(self.added_on)



def pincode_process(pincode_file=None):

    print "Pincode Adding ##########################",pincode_file,pincode_file[1:]


    book = open_workbook(pincode_file[1:])
    for j in range(0, book.nsheets - 1):
        sheet = book.sheet_by_index(j)
        for i in range(sheet.nrows):
            if i != 0:
                a = sheet.row_values(i)
                int_pin = int(a[0])
                Pincode(pincode=str(int_pin)).save()

    return True