Install & Compatibility
Where this runs
tested against v0.7.9 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.018s · 66.3MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 3.4s · import 0.018s · 67MB
65MB installed
● package 65MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
CurrentRequestUserMiddleware
✓ from crum import CurrentRequestUserMiddleware
get_current_request
✓ from crum import get_current_request
get_current_user
✓ from crum import get_current_user
impersonate
✓ from crum import impersonate
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.
# settings.py
MIDDLEWARE = [
# ... other middleware ...
'crum.CurrentRequestUserMiddleware',
# ... other middleware that might need request/user ...
]
# myapp/models.py (example)
from django.db import models
from django.conf import settings
from crum import get_current_user, get_current_request, impersonate
class AuditModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='created_%(class)ss'
)
last_modified_at = models.DateTimeField(auto_now=True)
last_modified_by = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='modified_%(class)ss'
)
request_ip = models.GenericIPAddressField(null=True, blank=True)
def save(self, *args, **kwargs):
user = get_current_user()
request = get_current_request()
if not self.pk: # Object is being created
if user and user.is_authenticated:
self.created_by = user
# Always update last_modified_by
if user and user.is_authenticated:
self.last_modified_by = user
# Capture IP address from request if available
if request:
self.request_ip = request.META.get('REMOTE_ADDR')
super().save(*args, **kwargs)
class Meta:
abstract = True
class MyItem(AuditModel):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
# Example of impersonation (e.g., in a background task or management command)
# from django.contrib.auth import get_user_model
# User = get_user_model()
# special_user = User.objects.get(username='system_user') # An existing user
# with impersonate(special_user):
# new_item = MyItem.objects.create(name='Automated Report')
# print(f"Item '{new_item.name}' created by: {new_item.created_by.username}")
Debug
Known issues
gotchaThe 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.fixThoroughly test django-crum within your specific Django and Python environment. Consider forking and maintaining compatibility if official updates are not released.
affects: <0.7.9 for recent Django/Python versions
gotchaDjango-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.fixUnderstand 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.
affects: All versions
deprecatedThe 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).fixMonitor the GitHub repository for activity. If critical bugs or security vulnerabilities arise, be prepared to contribute fixes or seek alternative solutions.
affects: All versions
Errors
Common errors & fixes
AttributeError: 'NoneType' object has no attribute '...' (e.g., 'username', 'id', 'META')
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).
fix1. 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)`.
ModuleNotFoundError: No module named 'crum'
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.
fixInstall the library using pip: `pip install django-crum`. Ensure you are installing it within the correct virtual environment if you are using one.
ImproperlyConfigured: 'crum.CurrentRequestUserMiddleware' is not a valid middleware class
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.
fixVerify that `django-crum` is correctly installed (`pip install django-crum`) and that the entry in your `MIDDLEWARE` setting is exactly `'crum.CurrentRequestUserMiddleware'`.
Upgrade
Version history
0.7.9latest on PyPI · released Nov 10, 2020
Audit
Dependencies
DjangorequiredCore framework dependency; django-crum is a Django middleware.