`django-typed-perms`: Typed Permissions for Django

If you have ever written a Django project using the permissions system, you probably felt that some of the experience is not that great. For me, this was the case, in every Django project that I’ve worked on in the last 5 years. I feel like the permissions system has all the functionality that I need, but it’s just not much friendly, specially with the latest python typing features. I wanted to change that scenario, and have written on a recent project a small improvement to the permissions system, and that worked very well, and I wanted to share with the community.

That’s why I created django-typed-perms. The project is available at pypi for installation, and it’s very “light”, no dependencies at all. I’ve first targeted it to most recent versions of python (>=3.12), but if you use a older version, feel free to open an issue if you face any errors.

The main goal of the package is for permission checking to be ‘type-safe’, and be able to be statically type checked with tools like mypy. With a big plus that is having “auto-complete” on your IDE. So, if you don’t want to write this type of code on your views, user_passes_test or any other place within your code:

# views.py
def some_view(request):
  if request.user and request.user.has_perm("some_app.view_somemodel"):
    ...

Then you’ll like this project! You can replace the above code with this:

# views.py
from some_app.models import SomeModel

def some_view(request):
  if SomeModel.user_has_permission(request.user, "view"):
    ...

This is a just simple (and not complete) example, but you can do a lot more! Let me know if you find this idea useful, or if you have any feature requests!

Cheers.

1 Like