Django admin: exclude field on change form only

后端 未结 4 1576
甜味超标
甜味超标 2020-12-13 16:23

If there a way to detect if information in a model is being added or changed.

If there is can this information be used to exclude fields.

Some pseudocode to

4条回答
  •  囚心锁ツ
    2020-12-13 16:48

    orwellian's answer will make the whole SubSectionAdmin singleton change its exclude property.

    A way to ensure that fields are excluded on a per-request basis is to do something like:

    class SubSectionAdmin(admin.ModelAdmin):
        # ...
        def get_form(self, request, obj=None, **kwargs):
            """Override the get_form and extend the 'exclude' keyword arg"""
            if obj:
                kwargs.update({
                    'exclude': getattr(kwargs, 'exclude', tuple()) + ('field',),
                })
            return super(SubSectionAdmin, self).get_form(request, obj, **kwargs)
    

    which will just inform the Form to exclude those extra fields.

    Not sure how this will behave given a required field being excluded...

提交回复
热议问题