我正在尝试向django管理员更改表单(视图)添加一个只读(代表性)id字段,例如我有这个模型:
class Foo(models.Model):
name = models.CharField(max_length=20)
def display_id(self):
# represent the AutoField (id) as "0001"
return str(self.id).zfill(4)
class FooAdminForm(forms.ModelForm):
display_id = forms.IntegerField(widget=ReadOnlyWidget)
class Meta:
model = Foo
class FooAdmin(admin.ModelAdmin):
form = FooAdminForm
fieldsets = (
(None, {'fields': ('name',)}),
('Extra info', {'fields': [
('display_id',),
]}),
)
这里有一些问题和非人:
我试过了:
应该/我可以:
ReadOnlyWidget
修复此行为?Form
代替ModelForm
即可避免数据/表格冲突。答案 0 :(得分:0)
您可以将readonly_fields添加到您的FooAdmin:
class FooAdmin(admin.ModelAdmin):
form = FooAdminForm
readonly_fields('id',)
fieldsets = (
(None, {'fields': ('name',)}),
('Extra info', {'fields': [
('display_id',),
]}),
)