Abzal Ali
Abzal Ali

Reputation: 199

Last digit not matched in the barcode image file, django

I have a model where the produc_attr is being stored in a CharField (string). Using the get_code method, I am converting the string of the product_attr to a number (13 digits), which is shown in my code_number column. Next, I'm generating a barcode image via the get_barcode method. The problem is: the number on the barcode PNG (image) file is wrong. That is, the last number out of a total of 13 digits is increased or decreased being printed which I have shown by adding a column (printed_number) at the end of the table. Any help would be appreciated.

class Inventory(models.Model):
    product          = models.ForeignKey('Product', blank=True, null=True, on_delete=models.SET_NULL)
    product_attr     = models.CharField(max_length=50, blank=True, null=True)
    code_number      = models.CharField(max_length = 13, blank=True, editable=False)
    barcode          = models.ImageField(upload_to = 'barcode/', blank=True)

    def __str__(self):
        return self.product

    def get_code_number(self):
        str1 = self.product_attr.encode()
        hash1 = hashlib.sha1()
        hash1.update(str1)
        return  str(int(hash1.hexdigest(), 16))[:13]

    def get_barcode(self):
        EAN = barcode.get_barcode_class('ean13')
        ean = EAN(f'{self.code_number}', writer=ImageWriter())
        buffer = BytesIO()
        ean.write(buffer)
        return self.barcode.save('barcode.png', File(buffer), save=False)

    def save(self, *args, **kwargs):
        self.code_number        = self.get_code_number()
        self.get_barcode()
        super(Inventory, self).save(*args, **kwargs)

enter image description here

Upvotes: 1

Views: 522

Answers (1)

Ashish srivastava
Ashish srivastava

Reputation: 11

You have to make a change in your save method. Store your generated ean number in your code_number field:

self.code_number=ean

Upvotes: 1

Related Questions