Debian Codegraph @

guardian/compat.py

raw
1 from django.conf import settings
2 from django.conf.urls import handler404, handler500, include
3 from django.contrib.auth import get_user_model
4 from django.contrib.auth.models import AnonymousUser, Group, Permission
5
6 __all__ = [
7 "Group",
8 "Permission",
9 "AnonymousUser",
10 "get_user_model",
11 "user_model_label",
12 "include",
13 "handler404",
14 "handler500",
15 ]
16
17 # Since get_user_model() causes a circular import if called when app models are
18 # being loaded, the user_model_label should be used when possible, with calls
19 # to get_user_model deferred to execution time
20
21 user_model_label = getattr(settings, "AUTH_USER_MODEL", "auth.User")
22
23
24 def get_user_model_path() -> str:
25 """Return the python path to the user model class.
26
27 Basically, if `AUTH_USER_MODEL` is set in settings it would be returned,
28 otherwise `auth.User` is returned.
29
30 Returns:
31 Python path to the user model class in the format
32 'app_label.ModelName'.
33 """
34 return getattr(settings, "AUTH_USER_MODEL", "auth.User")
35
36
37 def get_user_permission_full_codename(perm: str) -> str:
38 """Get the full codename for the user permission.
39
40 If standard `auth.User` is used, for 'change' perm this would return `auth.change_user`
41 and if `myapp.CustomUser` is used it would return `myapp.change_customuser`.
42
43 Returns:
44 Full codename for the user permission in the format
45 'app_label.<perm>_<usermodulename>'.
46 """
47 user_model = get_user_model()
48 model_name = user_model._meta.model_name
49 return f"{user_model._meta.app_label}.{perm}_{model_name}"
50
51
52 def get_user_permission_codename(perm: str) -> str:
53 """Get the codename for the user permission.
54
55 If standard `auth.User` is used, for 'change' perm this would return `change_user`
56 and if `myapp.CustomUser` is used, it would return `change_customuser`.
57
58 Returns:
59 Codename for the user permission in the format
60 `<perm>_<usermodulename>`
61 """
62 return get_user_permission_full_codename(perm).split(".")[1]