您好我想在查看或修改记录时使主键可见。但它不应该在django管理页面中编辑。因此我尝试了readonly_fields。但是,当我给出只读时,当我添加新记录时,我无法输入主键值。
这是我的admin.py
class EmployeeAdmin(admin.ModelAdmin):
search_fields = ['name']
list_display = ('name','id','dob','bill','mobile','email')
list_filter = ('bill','proj')
readonly_fields=('id',)
我的model.py是,
class Employee(models.Model):
id = models.IntegerField(max_length = 6,primary_key=True)
name = models.CharField(max_length = 100)
dob = models.DateField(verbose_name='Date Of Birth')
doj = models.DateField(verbose_name='Date Of Joining')
答案 0 :(得分:1)
您在admin.py中的课程应如下所示。请使用get_readonly_fields
执行此操作。
class EmployeeAdmin(admin.ModelAdmin):
search_fields = ['name']
list_display = ('name','id','dob','bill','mobile','email')
list_filter = ('bill','proj')
# readonly_fields=('id',)
def get_readonly_fields(self, request, obj=None):
if obj: # editing an existing object
return self.readonly_fields + ('id',)
return self.readonly_fields