Reputation: 2587
Im trying to get the current logged on users permissions
My current attempt below returns an error
from django.contrib.auth.models import Permission
from django.contrib.auth.models import User
permissions = Permission.objects.filter(user=User.id)
Error
int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'
does anyone know how I can do this? is there a simpler way?
Thanks
Upvotes: 1
Views: 14531
Reputation: 93
Also in Django 3.0 or above, according to the doc you can use:
self.request.user.get_user_permissions()
Returns a set of permission strings that the user has directly.
or to get all permissions:
self.request.user.get_all_permissions()
Upvotes: 5
Reputation: 6511
In case you are trying to put restrictions using group permissions, you can use the below decorator.
from django.contrib.auth.decorators import user_passes_test
Now you can use it to check if user is in a group.
@user_passes_test(lambda u: u.has_perm('Utilization.can_edit_invoice'))
@login_required
def edit_invoice(request, invoice_pk):
invoice = Invoice.objects.get(pk=invoice_pk)
if request.method == 'POST':
form = forms.AddInvoiceForm(request.POST, instance=invoice)
if form.is_valid():
form.save()
return HttpResponseRedirect(invoice.get_absolute_url())
else:
form = forms.AddInvoiceForm(instance=invoice)
args = {'form':form}
return render(request, 'Invoice/add_invoice.html', args)
Upvotes: 1
Reputation: 1980
Just updating @Alasdair answer for other users looking to do in oneline,
from django.db.models import Q
from django.contrib.auth.models import Permission
# All permissions
permissions = Permission.objects.filter(Q(user=user) | Q(group__user=user)).all()
Upvotes: 1
Reputation: 308999
You get the error because User
is the user model. You should use request.user
to access the logged-in user.
def my_view(request):
# Individual permissions
permissions = Permission.objects.filter(user=request.user)
# Permissions that the user has via a group
group_permissions = Permission.objects.filter(group__user=request.user)
You should probably check that the user is logged in (e.g. use login_required
).
Note and that the user may have permissions because of a group that they are in, or because they are a superuser (which is equivalent to having all permissions).
Upvotes: 9