Django UserForeignKey is a simple Django app that will give you a UserForeignKey model field for Django models.
This field extends a regular ForeignKey model field, and has the option to automatically set the currently logged in
user on insert and/or update.
Currently, Django 4.2, 5.2 and 6.0 are supported (Python 3.10+).
If you need support for Django 3.2 or 4.0/4.1, please fall back to version 0.5.0.
If you need support for the insecure and deprecated Django 1.11 and/or Python 2, please fall back to version 0.3.0.
There also is a video tutorial on YouTube that shows you basic functionality of this package.
- Install the package from pypi using pip:
pip install django-userforeignkey- Add
django_userforeignkeyto yourINSTALLED_APPSwithin your Django settings file:
INSTALLED_APPS = [
...
'django_userforeignkey',
]- Add
django_userforeignkey.middleware.UserForeignKeyMiddlewareto yourMIDDLEWAREsettings like this:
MIDDLEWARE = [
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
...
'django_userforeignkey.middleware.UserForeignKeyMiddleware',
]Make sure to insert the UserForeignKeyMiddleware middleware after AuthenticationMiddleware.
Just add UserForeignKey to your model like you would with any other foreign key.
from django.db import models
from django_userforeignkey.models.fields import UserForeignKey
class MyModel(models.Model):
my_data = models.CharField(max_length=64, verbose_name="Very important data that are somehow related to a user")
user = UserForeignKey(auto_user_add=True, verbose_name="The user that is automatically assigned", related_name="mymodels")The UserForeignKey behaves just like a normal foreign key to the user model (using settings.AUTH_USER_MODEL), and
thus also has properties such as related_name. However, whenever an object is created by calling an authenticated
view (admin, REST API, ...) which contains a request.user object, the request.user object is automatically
associated.
The configuration options are similar to Django's DateField.
auto_user: Automatically sets the current user everytime the object is saved (e.g., created or updated). This is useful for last modified by information.auto_user_add: Automatically sets the current user when the object is first created. This is useful for created by information.
git clone --recursive https://github.com/beachmachine/django-userforeignkey
cd django-userforeignkey
python -m venv ./venv
source venv/bin/activate
pip install -e .
pip install Django
cd tests/user_foreign_key_testapp
python manage.py test