How to disable add permission in the Django's admin page when the choices drop down field doesn't contain any data?

Issue

I have a model which has a template_name field which is shown as drop down in django admin.

template_id = models.CharField(max_length=255, choices=template_data, unique=True)

The template_data is getting populated from some other script.
The format of template_data is : (('123', 'car'), ('456', 'bike'))

This works fine when template_data has some values but when the template_data is an empty tuple, then I want to disable any add permission on admin page.

Currently when the redis is off, the add button is disabled but how to do the same when the template_data is an empty tuple?

Diasbled add permission when redis is off:

def has_add_permission(self, request, obj=None):
    is_redis = RedisCache.is_redis_available()
    if is_redis is not True:
        return False
    return True

RedisCache.is_redis_available(): Redis check is happening by calling is_redis_available func of RadisCache class.

Solution

Why cannot you load template_data directly in the permission method?

def has_add_permission(self, request, obj=None):
    if not template_data:
        return False
    is_redis = RedisCache.is_redis_available()
    if is_redis is not True:
        return False
    return True

Answered By – ChrisRob

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published