I want to make code field should be auto filled and auto increment in django admin. models.py
class GeneralDocumentType(models.Model):
code = models.CharField(max_length=10, null=False, unique=True)
name = models.CharField(max_length=100, null=False, unique=True)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.name
I want to show my code field default=DOC001, and it will show increment by 1 before adding data by user.How can I achieve this?..
CodePudding user response:
Django ModelAdmin has support for get_changeform_initial_data. In your admin you can override this method to get value based on the latest id info. For example:
class YourModelAdmin(admin.ModelAdmin):
...
def get_changeform_initial_data(self, request):
# getting the latest id
try:
latest_document_type = GeneralDocumentType.object.latest('id')
latest_id = latest_document_type.id 1
except GeneralDocumentType.DoesNotExist:
# incase there no object yet
latest_id = 0
return {'code': f'DOC{latest_id}'}
Note: this only work for adding new object, ModelAdmin. Doesn't work for InlineModelAdmin
