Django: Get current user in model save

后端 未结 6 1610
既然无缘
既然无缘 2020-12-04 23:29

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 p

6条回答
  •  我在风中等你
    2020-12-05 00:05

    I don't think that save_model method override is the best option. Imagine, for instance, that you want to save the user info or validate the model based on user info and that save() does not come from a view or the adminsite itself.

    What people are asking are constructions like those one:

    def save(..)
        self.user = current_user()
    

    or

    def save(..)
        user = current_user()
        if user.group == 'XPTO':
            error('This user cannot edit this record')
    

    The best approach I found so far is:

    https://bitbucket.org/q/django-current-user/overview

提交回复
热议问题