Search code examples
djangobarcode

how to generate barcode once


i have a problem, i generate barcode for field barcode in model Article

barcode=models.ImageField(upload_to='article/codes',blank=True)

On first insert of new object it saved normally but when i update it, the application generate new barcode, how can i make drop it just once?

models.py

from django.db import models
import random
from django.contrib.auth.models import User
import barcode
from barcode.writer import ImageWriter
from io import BytesIO
from django.core.files import File

`Status=(('0','Non'),('1','Oui'))
    
    class Article(models.Model):
        user= models.ForeignKey(User,blank=True,null=True,on_delete=models.CASCADE)
        numero=models.IntegerField(blank=True)
        barcode=models.ImageField(upload_to='article/codes',blank=True)
        nom = models.CharField(max_length=20)
        quantity=models.IntegerField(null=True)
        categorie=models.ForeignKey(Categorie,on_delete=models.CASCADE)
        date_entree=models.DateField(null=True)
        prix_achat=models.IntegerField(null=True)
        statut=models.CharField(max_length=2,null=True,default='0',choices=Status)
        
    
        def __str__(self):
            return self.nom
        
        def save(self,*args, **kwargs):
            EAN =barcode.get_barcode_class('upc')
            # rend=str(random.randint(2055,99999))
            # print(r)
            r=self.categorie.id+self.user.id
            rr=self.categorie.id+self.date_entree.day+self.prix_achat
            ean=EAN(str(self.categorie.id)+str(self.user.id)+str(r)+str(self.date_entree.year)+str(self.date_entree.month)+str(self.date_entree.day)+'34',writer=ImageWriter())
            buffer =BytesIO()
            ean.write(buffer)
            self.numero=ean.__str__()
            self.barcode.save(str({self.nom})+'.png',
            File(buffer),save=False)
            return super().save(*args, **kwargs)
       
        

    

Solution

  • Edit your save method:

    def save(self, *args, **kwargs):
        if self._state.adding:
            EAN =barcode.get_barcode_class('upc')
            # rend=str(random.randint(2055,99999))
            # print(r)
            r = self.categorie.id + self.user.id
            rr = self.categorie.id + self.date_entree.day + self.prix_achat 
            ean = EAN(str(self.categorie.id) + str(self.user.id) + str(r) + str(self.date_entree.year) + str(self.date_entree.month) + str(self.date_entree.day) + '34',writer=ImageWriter())
            buffer = BytesIO()
            ean.write(buffer)
            self.numero = ean.__str__()
            self.barcode.save(str({self.nom})+'.png',
            File(buffer),save=False)
        return super().save(*args, **kwargs)
    

    The code in the if block is executed only when the instance is created.