Make a pre-filled plum field as soon as in Django Admin
I want to make the slug field as read_only depending on another field value like "lock_slug".
Hence, there will be two conditions.
1) When "lock_slug" is false, the slug field is directly captured from the "title" field.
prepopulated_fields = {"slug": ("title",),}
2) When "lock_slug" is true, the slug field does it as read-only.
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 functions work great independently, but are problematic when both are used.
Means when I try to add get_readonly_fields () while editing then it gives an error due to prepopulated_fields. These two fail with each other.
A solution will be created to work as an administrator.
I also link to links
Making a read-only field in Django Admin based on the value of another field
django admin makes the field read-only when obj changes, but is required when adding a new obj
But these two do not work at the same time.
Thank,
Meenakshi
source to share
Here's another way:
class PostAdmin(admin.ModelAdmin):
list_display = (
'title',
'slug',
)
prepopulated_fields = {'slug': ('title',)}
def get_readonly_fields(self, request, obj=None):
if obj:
self.prepopulated_fields = {}
return self.readonly_fields + ('slug',)
return self.readonly_fields
source to share
As @Rexford pointed out, the most upvoted answer does not work for the latest django versions as you cannot make readonly a pre-filled field.
By the way, you can still get what you want, just override the method as well get_prepopulated_fields
using the same logic i.e.
class PageAdmin(admin.ModelAdmin):
prepopulated_fields = {
'slug': ('title', ),
}
def get_readonly_fields(self, request, obj=None):
if request.user.is_superuser:
return self.readonly_fields
return list(self.readonly_fields) + ['slug', ]
def get_prepopulated_fields(self, request, obj=None):
if request.user.is_superuser:
return self.prepopulated_fields
else:
return {}
source to share