I am wondering how can I get the current user id in the views.py? Furthermore, how can I get the current user's group id? Do I have to directly query the database using the user id? Thank you very much.
4 Answers
user = auth.get_user(request)
group = request.user.groups.values_list('name', flat=True).first()
Works Perfect!
So u can replace 'name' with 'id' to get group's ID

- 883
- 11
- 24
View functions get request
as one of their parameters. Assuming you're using the built in auth app, the current user (if any) will be request.user
. This may be a representation of an anonymous user if the session does not have a logged-in user - see the docs if you don't want to allow that.
Users can be in many groups, so I'm not quite sure what you mean by "group id". The user's groups are available as a standard many-to-many field, as request.user.groups
. That's a manager object, so you can apply filters and such to it - to get them all, request.user.groups.all()
.

- 36,326
- 7
- 90
- 83
-
Thanks! I need the group id because I have extended the group models, so I think I would need the group id to get field values out. But with request.user.groups.all(), it seems that it only returns the name of the group... – Robert Nov 10 '13 at 18:13
-
`groups.all()` returns the actual `Group` objects. If you `print` it they will be represented using their names, but `groups.all()[0].somefield` should also work. Unless your extensions to the models have changed the relationship. You need to show your custom model code in your question if that's the case. – Peter DeGlopper Nov 10 '13 at 18:35
-
Hey man, I have another question: http://stackoverflow.com/questions/19898284/django-why-the-manytomany-choice-box-only-has-on-side won't you help me with it? – Robert Nov 11 '13 at 03:19
If there is one and only one group per user in your use case, you can get that group by using request.user.groups.get()
. objects.get()
works somewhat similar to objects.all()[0]
. So it will fail when there are more than one group for that user.
https://github.com/django/django/blob/master/django/db/models/query.py
def get(self, *args, **kwargs):
"""
Performs the query and returns a single object matching the given
keyword arguments.
"""
clone = self.filter(*args, **kwargs)
if self.query.can_filter():
clone = clone.order_by()
clone = clone[:MAX_GET_RESULTS + 1]
num = len(clone)
if num == 1:
return clone._result_cache[0]
if not num:
raise self.model.DoesNotExist(
"%s matching query does not exist." %
self.model._meta.object_name)
raise self.model.MultipleObjectsReturned(
"get() returned more than one %s -- it returned %s!" % (
self.model._meta.object_name,
num if num <= MAX_GET_RESULTS else 'more than %s' % MAX_GET_RESULTS
)
)
If you are after categorising your users, just extend the user model and set a foreign key field. Using permission groups for that matter doesn't seem like a good approach to me.

- 4,258
- 1
- 16
- 26
If you debug with the break point on the method below,
@csrf_exempt
def auth_check(request):
return HttpResponse(str(request.user)) # <- breakpoint
you can see that there are user.groups
in the request.
As shown in the highlighted part above, you can find the groups name to which the user belongs.
you can easily get user group id
request.user.groups.name

- 569
- 1
- 6
- 17