database
| id | salary_number |
| --- | ------------- |
| 1 | 1042 |
models.py
class user(AbstractUser):
salary_number = models.CharField(max_length=4, unique=True, null=True, blank=True)
def __str__(self):
return f'{self.salary_number[-3:]}'
admin.py
class UserAdmin(admin.ModelAdmin):
fields = ('salary_number[-3:]',)
def get_readonly_fields(self, request, obj=None):
return ['salary_number'] if obj else []
I would like to show Salary number: 042 in admin fields instead of 1042. Is it possible?
How can I add number 1 to the salary_number after click save new form?
CodePudding user response:
You can use '__str__'
as field:
class UserAdmin(admin.ModelAdmin):
readonly_fields = ('__str__',)
But this makes it unclear what the field is doing. Likely it is better to make a callable that describes that this is the last digits of the salary number:
class UserAdmin(admin.ModelAdmin):
readonly_fields = ('salary_digits',)
@admin.display(description='Salary digits')
def salary_digits(self, obj):
if obj.salary_number is not None:
return obj.salary_number[-3:]