Question

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.

Was it helpful?

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top