Deepankar Bajpeyi
Deepankar Bajpeyi

Reputation: 5869

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.

Upvotes: 2

Views: 109

Answers (1)

codeape
codeape

Reputation: 100786

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()

Upvotes: 2

Related Questions