Django:在模型保存中获取当前用户 [英] Django: Get current user in model save

查看:33
本文介绍了Django:在模型保存中获取当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在models.py的save方法中获取当前登录的用户(request.user).我想查看用户的角色,看看是否可以根据他的角色进行一些操作.

I want to get the currently logged in user (request.user) in the save method of models.py. I want to check the role of the user and see if it can perform some operations based on his role.

models.py:

class TimeSheet(models.Model):
    check_in_time = models.TimeField()
    check_out_time = models.TimeField()

class Tasks(models.Model):
    time_sheet = models.ForeignKey(TimeSheet)
    project = models.ForeignKey(Project)
    start_time = models.TimeField()
    end_time = models.TimeField()

    def save(self, *args,**kwargs):
        project = SpentTime.objects.get(project__project__id = self.project.id)
        start = datetime.datetime.strptime(str(self.start_time), '%H:%M:%S')
        end = datetime.datetime.strptime(str(self.end_time), '%H:%M:%S')
        time = float("{0:.2f}".format((end - start).seconds/3600.0))

        if common.isDesigner(request.user):
            SpentTime.objects.filter(project__project__id = self.project.id).update(design = float(project.design) + time)

        if common.isDeveloper(request.user):
            SpentTime.objects.filter(project__project__id = self.project.id).update(develop = float(project.develop) + time)

        super(Tasks, self).save(*args, **kwargs)

此处 Tasks 模型用作 Timesheet 模型中的内联模型.我想检查当前登录用户的角色并根据用户的角色更新另一个模型.这里我需要 request.user 来检查当前用户的角色.我没有使用任何表单或模板,而是完全使用了 Django admin.是否有任何方法可以在 save 方法中获取 request.user 或在 admin.py 中检查和更新另一个模型中的值?

Here the Tasks model is being used as inline in Timesheet model. I want to check the role of the currently logged in user and update another model based on the user's role. Here I need request.user to check the role of the current user. I am not using any forms or templates and completely making use of Django admin. Is there any method to get request.user in the save method or to check and update the values in another model in admin.py?

推荐答案

您可以从另一个角度解决这个问题.您应该覆盖 AdminSites save_model 方法,而不是更改模型保存方法.在那里您将拥有请求对象并可以访问您已经指出的登录用户数据.

You can tackle this problem from another angle. Instead of changing the models save method you should override the AdminSites save_model method. There you'll have the request object and can access the logged in user data as you already pointed out.

看看文档的这一章:Django ModelAdmin 文档 save_model

这篇关于Django:在模型保存中获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆