Search code examples
pythondjangodjango-admindjango-users

Django : how to Identify who is saving the model from program?


How do I check from the django code, which User is saving a model currently ?

I need to throw Validation Errors or assign some permissions to him from that.


Solution

  • Assuming you execute the model.save() from a view function, you can get the current user with request.user.

    from django.contrib.auth.models import Permission
    
    def myview(request):
        model = Model(...)
        model.save()
        permission = Permission.objects.get(codename="...")
        request.user.user_permissions.add(permission)
    

    EDIT: Access the request in a form

    The simplest way to get at the request from your form validation code is probably to set a attribute on the form instance:

    def myview(request):
        ...
        form = SomeForm(...)
        form.request = request
    

    Inside your form validation logic you can now use self.request to access the user:

    class SomeForm(...):
        def clean_somefield(self):
            data = self.cleaned_data["somefield"]
            if self.request.user....:
                 raise ValidationError()