pythondjangodjango-admindjango-admin-filtersdjango-admin-tools

Auto increament the invoice number in django backend for new invoice


I want to auto increament the invoice number which is 3 digits char and 4 digits number.

class Invoice:
    invoice_no = models.CharField(max_length=500, null=True, blank=True, validators=[RegexValidator(regex='^[a-zA-Z0-9]*$',message='Invoice must be Alphanumeric',code='invalid_invoice number'),])

I register this model in backend. But now when i click on create invoice in admin the invoice should be auto filled. When i again click on create new invoice in admin, the invoice_number should be incremented by one and should be auto field.

Ex for Invoice number MAG0001, MAG0002, MAG0003 etc and this should be auto field in admin when i click on create new invoice.


Solution

  • Define a function to generate invoice number.

    def increment_invoice_number():
        last_invoice = Invoice.objects.all().order_by('id').last()
        if not last_invoice:
             return 'MAG0001'
        invoice_no = last_invoice.invoice_no
        invoice_int = int(invoice_no.split('MAG')[-1])
        new_invoice_int = invoice_int + 1
        new_invoice_no = 'MAG' + str(new_invoice_int).zfill(4)
        return new_invoice_no
    

    Now use this function as default value in your model filed.

    invoice_no = models.CharField(max_length=500, default=increment_invoice_number, null=True, blank=True)
    

    This is just an idea. Modify the function to match your preferred invoice number format.