django admin make a field read-only when modifying obj but required when adding new obj

后端 未结 7 1554
甜味超标
甜味超标 2020-12-04 09:31

In admin I would like to disable a field when modifying object, but make it required when adding new object.

Whats the django way to go about this one?

7条回答
  •  自闭症患者
    2020-12-04 10:00

    The situation with inline forms is still not fixed for Django 2.2.x but the solution from John is actually pretty smart.

    Code slightly tuned to my situation:

    class NoteListInline(admin.TabularInline):
    """ Notes list, readonly """
        model = Note
        verbose_name = _('Note')
        verbose_name_plural = _('Notes')
        extra = 0
        fields = ('note', 'created_at')
        readonly_fields = ('note', 'created_at')
    
        def has_add_permission(self, request, obj=None):
        """ Only add notes through AddInline """
        return False
    
    class NoteAddInline(admin.StackedInline):
        """ Notes edit field """
        model = Note
        verbose_name = _('Note')
        verbose_name_plural = _('Notes')
        extra = 1
        fields = ('note',)
        can_delete = False
    
        def get_queryset(self, request):
            queryset = super().get_queryset(request)
            return queryset.none()  # no existing records will appear
    
    @admin.register(MyModel)
    class MyModelAdmin(admin.ModelAdmin):
        # ...
        inlines = (NoteListInline, NoteAddInline)
        # ...
    

提交回复
热议问题