{"id":6593,"library":"django-crum","title":"Django-CRUM","description":"Django-CRUM (Current Request User Middleware) captures the current request and user in thread local storage. It enables Django applications to check permissions, capture audit trails, or access the current request and user without requiring the request object to be passed directly. It also provides a context manager for temporarily impersonating another user. The current version is 0.7.9, released on November 10, 2020, and it is tested against various Django versions from 1.11 up to 4.0, and Python versions from 3.4 to 3.9.","status":"maintenance","version":"0.7.9","language":"python","source_language":"en","source_url":"https://github.com/ninemoreminutes/django-crum/","tags":["django","middleware","request","user","authentication","authorization","thread-local"],"install":[{"cmd":"pip install django-crum","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Core framework dependency; django-crum is a Django middleware.","package":"Django"}],"imports":[{"symbol":"CurrentRequestUserMiddleware","correct":"from crum import CurrentRequestUserMiddleware"},{"symbol":"get_current_request","correct":"from crum import get_current_request"},{"symbol":"get_current_user","correct":"from crum import get_current_user"},{"symbol":"impersonate","correct":"from crum import impersonate"}],"quickstart":{"code":"# settings.py\nMIDDLEWARE = [\n    # ... other middleware ...\n    'crum.CurrentRequestUserMiddleware',\n    # ... other middleware that might need request/user ...\n]\n\n# myapp/models.py (example)\nfrom django.db import models\nfrom django.conf import settings\nfrom crum import get_current_user, get_current_request, impersonate\n\nclass AuditModel(models.Model):\n    created_at = models.DateTimeField(auto_now_add=True)\n    created_by = models.ForeignKey(\n        settings.AUTH_USER_MODEL, \n        on_delete=models.SET_NULL, \n        null=True, \n        blank=True,\n        related_name='created_%(class)ss'\n    )\n    last_modified_at = models.DateTimeField(auto_now=True)\n    last_modified_by = models.ForeignKey(\n        settings.AUTH_USER_MODEL, \n        on_delete=models.SET_NULL, \n        null=True, \n        blank=True,\n        related_name='modified_%(class)ss'\n    )\n    request_ip = models.GenericIPAddressField(null=True, blank=True)\n\n    def save(self, *args, **kwargs):\n        user = get_current_user()\n        request = get_current_request()\n        \n        if not self.pk: # Object is being created\n            if user and user.is_authenticated:\n                self.created_by = user\n        \n        # Always update last_modified_by\n        if user and user.is_authenticated:\n            self.last_modified_by = user\n        \n        # Capture IP address from request if available\n        if request:\n            self.request_ip = request.META.get('REMOTE_ADDR')\n\n        super().save(*args, **kwargs)\n\n    class Meta:\n        abstract = True\n\nclass MyItem(AuditModel):\n    name = models.CharField(max_length=255)\n\n    def __str__(self):\n        return self.name\n\n# Example of impersonation (e.g., in a background task or management command)\n# from django.contrib.auth import get_user_model\n# User = get_user_model()\n# special_user = User.objects.get(username='system_user') # An existing user\n# with impersonate(special_user):\n#    new_item = MyItem.objects.create(name='Automated Report')\n#    print(f\"Item '{new_item.name}' created by: {new_item.created_by.username}\")","lang":"python","description":"To use django-crum, first install the package. Then, add `CurrentRequestUserMiddleware` to your Django project's `MIDDLEWARE` setting. You can then import and use `get_current_request()`, `get_current_user()`, or the `impersonate()` context manager within your application code, for example, in model `save` methods or custom logic, to access the current request or user."},"warnings":[{"fix":"Thoroughly test django-crum within your specific Django and Python environment. Consider forking and maintaining compatibility if official updates are not released.","message":"The latest release (0.7.9) is from November 2020. While it explicitly mentions testing up to Django 4.0, newer Django versions (like 5.x, 6.x) and Python versions (3.10+) might not be fully supported or tested, which could lead to unexpected behavior or require manual compatibility adjustments.","severity":"gotcha","affected_versions":"<0.7.9 for recent Django/Python versions"},{"fix":"Understand the implications of thread-local storage in your deployment environment. For ASGI applications, ensure proper context propagation mechanisms are in place or consider alternative approaches if `django-crum` exhibits unexpected behavior.","message":"Django-CRUM relies on Python's thread-local storage to capture the current request and user. This approach is primarily designed for traditional WSGI (synchronous) environments. In modern asynchronous (ASGI) Django applications or highly concurrent multi-threaded setups, relying solely on thread-local storage without careful consideration of task/thread boundaries can lead to incorrect context or race conditions.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Monitor the GitHub repository for activity. If critical bugs or security vulnerabilities arise, be prepared to contribute fixes or seek alternative solutions.","message":"The project is still classified as 'Development Status :: 4 - Beta' on PyPI and has not seen a new release since November 2020. This indicates that it might not be actively maintained for new features or prompt bug fixes, and future breaking changes are possible (though less likely given its current maintenance state).","severity":"deprecated","affected_versions":"All versions"}],"env_vars":null,"search_vec":"'0.7.9':62 '1.11':77 '10':66 '2020':67 '3.4':85 '3.9':87 '4.0':80 'access':32 'also':48 'anoth':56 'applic':24 'audit':29 'authent':92 'author':93 'captur':11,28 'check':26 'context':51 'crum':3,6 'current':7,13,34,59 'direct':46 'django':2,5,23,74,88 'django-crum':1,4 'enabl':22 'imperson':55 'local':19,96 'manag':52 'middlewar':10,89 'novemb':65 'object':42 'pass':45 'permiss':27 'provid':49 'python':82 'releas':63 'request':8,14,35,41,90 'requir':39 'storag':20 'temporarili':54 'test':71 'thread':18,95 'thread-loc':94 'trail':30 'user':9,16,37,57,91 'various':73 'version':60,75,83 'without':38","created_at":"2026-04-15T18:34:34.062793+00:00","updated_at":"2026-04-16T14:29:44.262279+00:00","problems":[{"fix":"1. Ensure `crum.CurrentRequestUserMiddleware` is correctly added to your `MIDDLEWARE` setting in `settings.py`. It should generally be placed after Django's `SessionMiddleware` and `AuthenticationMiddleware`. 2. Always check if the returned object is not `None` before accessing its attributes, for example: `user = get_current_user(); if user: print(user.username)`.","cause":"This error typically occurs when `crum.get_current_user()` or `crum.get_current_request()` returns `None`, meaning no request or user is available in the thread-local storage, and the code attempts to access an attribute on that `None` object. This usually happens when the middleware is not properly configured, or the functions are called outside of a request context (e.g., in a management command, a background task, or during application initialization).","error":"AttributeError: 'NoneType' object has no attribute '...' (e.g., 'username', 'id', 'META')"},{"fix":"Install the library using pip: `pip install django-crum`. Ensure you are installing it within the correct virtual environment if you are using one.","cause":"The `django-crum` library is not installed in the Python environment, or the Python environment where the application is running does not have access to the installed package.","error":"ModuleNotFoundError: No module named 'crum'"},{"fix":"Verify that `django-crum` is correctly installed (`pip install django-crum`) and that the entry in your `MIDDLEWARE` setting is exactly `'crum.CurrentRequestUserMiddleware'`.","cause":"This error indicates that Django cannot find the `CurrentRequestUserMiddleware` class at the specified path in your `MIDDLEWARE` settings. This is often due to a typo in the middleware path or an issue with the package installation.","error":"ImproperlyConfigured: 'crum.CurrentRequestUserMiddleware' is not a valid middleware class"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"0.7.9","cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/ninemoreminutes/django-crum","docs":"https://django-crum.rtfd.org/","changelog":null,"pypi":"https://pypi.org/project/django-crum/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["aws","type-stubs","http-networking","web-framework","testing"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-06-28","next_check":"2026-07-28","install_tag":null}}