Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django admin – prevent changing a field after it has become true

I have a model registred in admin.py:

class OrderAdmin(admin.ModelAdmin):
    list_display = ('org_name', 'address', 'total_cost', 'phone', 'data_time', 'is_called', 'is_payed')
    search_fields = ('org_name', 'phone')
    list_filter = ('data_time', 'total_cost', 'data_time')
    list_editable = ('is_called', 'is_payed')
    readonly_fields = ('data_time', 'user', 'total_cost')
    inlines = [OrderItemsAdmin, ]

I need to do something like:

class OrderAdmin(admin.ModelAdmin):
    list_display = ('org_name', 'address', 'total_cost', 'phone', 'data_time', 'is_called', 'is_payed')
    search_fields = ('org_name', 'phone')
    list_filter = ('data_time', 'total_cost', 'data_time')
    list_editable = ('is_called', 'is_payed')
    readonly_fields = ('data_time', 'user', 'total_cost')
    inlines = [OrderItemsAdmin, ]

    if 'is_called' == True:
        readonly_fields.append('is_called')

I think that it’s possible, so the question is how to do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can make use of ModelAdmin.get_readonly_fields() method

Give this a try

class OrderAdmin(admin.ModelAdmin):
    ...

    def get_readonly_fields(self, request, obj=None):
        readonly_fields = super(OrderAdmin, self).get_readonly_fields(request, obj)

        if obj.is_called:
            readonly_fields.append("is_called")
            return readonly_fields

        return readonly_fields
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading