I want to autocomplete 2 fields:
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.
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.
答案 0 :(得分:1)
May be the solution with default user by Middleware help you.
答案 1 :(得分:1)
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')
然后在您看来,您可以这样做:
form.created_by = request.user
form.updated_by = request.user
由进行此操作的当前用户自动完成。
可能是我没有理解你的问题,所以可能这就是你要找的东西:How to auto insert the current user when creating an object in django admin?
答案 2 :(得分:0)
非常简单,只需添加到您的字段:editable = False 像这样:
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, related_name='created_by')