Django:保存模型时填充用户 ID [英] Django: Populate user ID when saving a model
问题描述
我有一个带有 created_by 字段的模型,该字段链接到标准 Django 用户模型.保存模型时,我需要使用当前用户的 ID 自动填充它.我不能在 Admin 层执行此操作,因为该站点的大部分内容都不会使用内置的 Admin.任何人都可以就我应该如何处理这个问题提出建议吗?
I have a model with a created_by field that is linked to the standard Django User model. I need to automatically populate this with the ID of the current User when the model is saved. I can't do this at the Admin layer, as most parts of the site will not use the built-in Admin. Can anyone advise on how I should go about this?
推荐答案
更新 2020-01-02
⚠ 以下答案从未更新到最新的 Python 和 Django 版本.自从几年前写这篇文章以来,已经发布了一些软件包来解决这个问题.现在我强烈推荐使用django-crum
,它实现了相同的技术,但有测试并定期更新:https://pypi.org/project/django-crum/
UPDATE 2020-01-02
⚠ The following answer was never updated to the latest Python and Django versions. Since writing this a few years ago packages have been released to solve this problem. Nowadays I highly recommend usingdjango-crum
which implements the same technique but has tests and is updated regularly: https://pypi.org/project/django-crum/
最不麻烦的方法是使用 CurrentUserMiddleware
将当前用户存储在线程本地对象中:
The least obstrusive way is to use a CurrentUserMiddleware
to store the current user in a thread local object:
from threading import local
_user = local()
class CurrentUserMiddleware(object):
def process_request(self, request):
_user.value = request.user
def get_current_user():
return _user.value
现在您只需要在认证中间件之后将该中间件添加到您的 MIDDLEWARE_CLASSES 中.
Now you only need to add this middleware to your MIDDLEWARE_CLASSES after the authentication middleware.
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
...
'current_user.CurrentUserMiddleware',
...
)
您的模型现在可以使用 get_current_user
函数访问用户,而无需四处传递请求对象.
Your model can now use the get_current_user
function to access the user without having to pass the request object around.
from django.db import models
from current_user import get_current_user
class MyModel(models.Model):
created_by = models.ForeignKey('auth.User', default=get_current_user)
提示:
如果您使用的是 Django CMS,您甚至不需要定义自己的 CurrentUserMiddleware 但可以使用 cms.middleware.user.CurrentUserMiddleware
和 cms.utils.permissions.get_current_user
函数来检索当前用户.
Hint:
If you are using Django CMS you do not even need to define your own CurrentUserMiddleware but can use cms.middleware.user.CurrentUserMiddleware
and the cms.utils.permissions.get_current_user
function to retrieve the current user.
这篇关于Django:保存模型时填充用户 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!