get user group name from a specific text in django

Question:

In django, user posts in a simple HTML form. In form, there is a field which called "technician_name". I’m getting the post with "name attribute" and write it to database.

I want additional thing: after I take the name attribute, I want to check the group of technician. Simply: I want to check user’s group according to specific text.

For example: user posted the "John Doe".

if request.method == 'POST'    
    action_man = request.POST.get('technician_name')
Output:
action_man = "John Doe"

I need this action_man‘s user group. The action_man’s name same with username, so I can query in django auth.

Note: I don’t need the logged in user’s group. I need action man’s group.

Asked By: piseynir

||

Answers:

I hope I understand you correctly. You have some String and want to filter your groups with that string?

from django.contrib.auth.models import Group

some_string = "John Doe"
qs = Group.objects.filter(name=some_string)

# alternatively if only one hit is wanted
qs = Group.objects.get(name=some_string)

Edit

OP writes: "[..]John Doe belongs to one group in django auth groups. I want to get that group name."

user = User.objects.get(name="John Doe")
user_groups = [group.name for group in user.groups.all()]
print(f"John Doe belongs to the following groups: {user_groups}"
Answered By: Tarquinius
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.