Login

Number generator to autofill a field

Author:
pizte
Posted:
July 1, 2010
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

Number format: number/year

Purpose: When the user adds a new bill, the "number" field will be automatically filled with the appropriate number.

  • The snippet automatically increments the bill number based in the highest number available. This is because in the use case, the user could start by any number, and we couldn't use the PK number (p.e. if the user first object number is 324/10, using the PK will convert it to 1/10)

NOTE: bill_type is a Boolean value to mark if the bill is outgoing or ingoing. Since we only need to mark the outgoing ones, we filter through this field.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Bill(models.Model):
    
    def __number():
        """
        Automatic bill number generator.
        
        bill_emmited: returns a list with all the bill objects
                      with bill_type=False
        latest_object: from bill_emmited get the latest one
                       and convert it to string to manipulate
        first_number: returns the first number of the latest_object field
                      and adds 1
        If there's no bill objects, return first_number=1. The overall
        function returns either an incremented first_number slash year or
        one slash year.
        """
        current_year = date.today().strftime('%y')
        try:
            bill_emmited = Bill.objects.filter(bill_type__exact=False)
            latest_object = bill_emmited.latest('number').__str__()
            first_number = int(latest_object.split("/")[0]) + 1
        except Bill.DoesNotExist:
            first_number = 1
        return '%s/%s' % (first_number, current_year)
        
    number = models.CharField(_('Bill number'), max_length=10, unique=True, \
    default=__number)
    bill_type = models.BooleanField()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 4 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.