简体   繁体   中英

How to Process Uploaded file in Django Model save method

From the django default admin panel, I need to store all pin-codes that uploaded from an excel file

for that I developed two models Pincodes and UploadPinFile.

I am trying to save all pincodes to Pincode Model from UploadPinFile's save method

but it returns me an error given bellow

coercing to Unicode: need string or buffer, FieldFile found

The two model defanitions are given below

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

Example Pincode file contains

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

You just create a def for procees. And it will call from inside save() method ...

You Just Follow this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM