[Django]-Django: how to get the current user's group id

5👍

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

6👍

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

0👍

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.

0👍

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.

Imgur

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

Leave a comment