avoid error: 'NoneType' object has no attribute in django model admin

I need to show if a client is having a related contract active or no in customized field in django model admin I tried to use try: but it does not work unfortunately

here the original code:

class ClientAdmin(ExportModelAdminMixin, ModelAdmin):
    model = Client
    menu_icon = "pick"
    menu_order = 100
    exclude_from_explorer = False
    list_display = ["name", "is_active"]
    search_fields = ["name"]
    list_filter = [ClientFilter]
    index_template_name = "wagtailadmin/export_csv.html"
    csv_export_fields = ["name"]

    def is_active(self, client: Client) -> bool:
        any(site.current_contract.is_active for site in client.sites.all())
        
    is_active.boolean = True  # type: ignore
    is_active.short_description = _("active confirmation")  # type: ignore

I got the error:

File "/home/oladhari/reachat-v4/Reachat-v4/backend/crm/admin.py", line 61, in is_active
any(site.current_contract.is_active for site in client.sites.all())
File "/home/oladhari/reachat-v4/Reachat-v4/backend/crm/admin.py", line 61, in <genexpr>
any(site.current_contract.is_active for site in client.sites.all())
AttributeError: 'NoneType' object has no attribute 'is_active'

to resolve this error I tried to use try: and changed the customized field to this:

def is_active(self, client: Client) -> bool:
        try:
            any(site.current_contract.is_active for site in client.sites.all())
        except ObjectDoesNotExist:
            return False
        else:
            return any(site.current_contract.is_active for site in client.sites.all())

but still having the same error unfortunately please could you help me to avoid this error, thank you


Solution 1:

Why not use a normal query for the is_active method?

So, something like:

 def is_active(self, client: Client) -> bool:
        return client.sites.filter(current_contract__is_active=True).exists()