Search code examples
pythondjangodjango-adminreadonlyslug

Make the prepopulated slug field as readonly in Django Admin


I want to make the slug field as read_only depending on the other field value like "lock_slug".

Means There will be Two conditions.

1) When value of "lock_slug" is false then the slug field directly prepopulated from the field "title".

prepopulated_fields = {"slug": ("title",),}

2) When value of "lock_slug" is true then the slug field make as readonly.

def get_readonly_fields(self, request, obj = None):
    if obj and obj.lock_slug == True:
        return ('slug',) + self.readonly_fields        
    return self.readonly_fields

These two works fine independently, but problematic when used both.

Means when I try to add get_readonly_fields() on edit then it gives error because of prepopulated_fields.These two crashes with each other.

There will be any solution for working both on admin side.

I also refer below links

Making a field readonly in Django Admin, based on another field's value

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

But not working these two at the same time.

Thanks,

Meenakshi


Solution

  • We can not make the prepoluted field as read_only. So I create the new field which is not prepopulated and perform the action on that field and my problem get solved.