PermissionRequiredMixin not importable before apps ready?

41 views
Skip to first unread message

Christian González

unread,
Feb 7, 2023, 9:14:22 AM2/7/23
to django-developers

Hi devs,

I have a weird problem that I first thought is on my side. But after thinking about it, it could be fixed in Django with a no-brainer and backwards-compatible. But before filing a bug, I'd like to ask here for your opinion - it may be that I am stil wrong.

I use a custom view mixin class that is used for some views in my application, and it is also an interface for a plugin system, so it will be loaded at **declaration time** (before apps & models are loaded).

All good so far, but nearly all of my views need django's PermissionRequiredMixin. So I decided to  add PermissionRequiredMixin directly to my parent mixin class (which gets loaded early). Neither my class nor PermissionRequiredMixin uses models, but just by loading `django.contrib.auth.mixins` there is one line that hickups Django:

from django.contrib.auth.views import redirect_to_login

This leads to importing "User", hence a model, and Django throws a AppRegistryNotReady exception.

In django.contrib.auth.mixins, the only method that uses "redirect_to_login()" is line 60 in handle_no_permission().

This "problem" could be easily solved if the import statement is done locally in handle_no_permission, and not at module level - which leads to the django.contrib.auth.mixins being usable in early Django (before model loading).

The only side effect I could think of, that it adds some loading time during that method call the first time - but reduces the same loading time at startup. Which is neglegible IMHO.

Please tell me if I'm completely wrong - or if this is worth a bug report/PR.

Christian

-- 
Dr. Christian González
https://nerdocs.at

charettes

unread,
Feb 7, 2023, 12:56:09 PM2/7/23
to Django developers (Contributions to Django itself)
Hello Christian,

Could you possibly provide a minimal project setup that reproduces your issue?

From what I can see here you're running into this issue because the `django.contrib.auth.views` module calls `get_user_model` at initialization time but the latter has been passing `require_ready=False` to `apps.get_model` for a while[0] so it's hard to tell whats to blame without a proper traceback.

I suspect you might have an import cycle between involving your custom user model and some of your dependencies on django.contrib.auth.

Cheers,
Simon

Reply all
Reply to author
Forward
0 new messages