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

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:

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

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 :

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()

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