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

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

问题描述

我想在models.py的保存方法中获取当前登录的用户(request.user)。我想检查用户的角色,并根据他的角色执行一些操作。我已经下载了models.py代码。

I want to get current logged in user(request.user) in save method of models.py. I want to check the role of the user and perform some operations based on his role. I have given the models.py code below.

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)

这里任务模型正在使用强力时间表模型中的内联。我想检查当前登录用户的角色,并根据用户的角色更新另一个模型。这里我需要 request.user 来检查当前用户的角色。我没有使用任何形式或模板,并完全使用django管理员。所以有什么方法可以在模型保存方法中获取 request.user ,或者检查并更新admin.py中另一个模型中的值。

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

我已经检查了stackoverflow中的大部分类似问题,没有一个为我提供完美的解决方案。所以请提供一个解决这个问题的答案。感谢提前。

I have checked most of the similar questions in stackoverflow and none them provide me a perfect solution. So please provide me an answer to fix this. Thanks in advance.

推荐答案

您可以从另一个角度解决这个问题。而不是更改模型保存方法,您应该覆盖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天全站免登陆