简体   繁体   English

Django request.user是模型,适用于管理员和普通用户

[英]Django request.user is model, for admin and normal user

I want to autocomplete 2 fields: 我想自动完成2个字段:

created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='created_by')
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='updated_by')

for normal users and for django admin. 对于普通用户和django管理员。

If for normal users I can use get request.user from my view(found some solutions here on the site),but this is not the case for admin/staff because I don't control the views, so I'm searching for a solution at the Model level by overwriting the save function. 如果对于普通用户,我可以从我的视图中使用get request.user(可在此处找到一些解决方案),但是对于admin / staff而言,情况并非如此,因为我无法控制这些视图,因此我正在搜索通过覆盖保存功能在模型级别解决方案。

May be the solution with default user by Middleware help you. 中间件可能是默认用户的解决方案,可以帮助您。

django-populate-user-id-when-saving-a-model django在保存模型时填充用户ID

from django.contrib.auth.models import User

created_by = models.ForeignKey(User, related_name='created_by')

updated_by = models.ForeignKey(User, related_name='updated_by')

Then in your view, you can do this : 然后,您可以执行以下操作:

form.created_by = request.user
form.updated_by = request.user

It's going to autocomplete by the current user who made the action. 它将由执行此操作的当前用户自动完成。

May be I didn't understant your question, so may be this is what you're looking for : How to auto insert the current user when creating an object in django admin? 也许我不是很了解您的问题,所以这可能就是您要查找的内容: 在django admin中创建对象时如何自动插入当前用户?

非常简单,只需将其添加到您的字段即可:editable = False像这样:

created_by = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, related_name='created_by')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM