2010-02-11 12 views
24

ho provato seguente Codice con l'aiuto del django.contrib.auth.User e django.contrib.auth.Groupc'è un semplice per ottenere i nomi dei gruppi di un utente in Django

for g in request.user.groups: 
    l.append(g.name) 

Ma che non è riuscito e ho ricevuto in seguito Errore:

TypeError at/
'ManyRelatedManager' object is not iterable 
Request Method: GET 
Request URL: http://localhost:8000/ 
Exception Type: TypeError 
Exception Value:  
'ManyRelatedManager' object is not iterable 
Exception Location: C:\p4\projects\...\users.py in permission, line 55 

Grazie per qualsiasi aiuto!

risposta

50
for g in request.user.groups.all(): 
    l.append(g.name) 

o con recente Django

l = request.user.groups.values_list('name',flat=True) 
+0

funziona come un fascino! – icn

4
user.groups.all()[0].name == "groupname" 
+1

Com'è pertinente alla domanda? – Aaron

+0

Vero, non rilevante per la domanda corrente, ma ha aiutato gli altri a ottenere il gruppo con un nome specifico. –

5

questo è meglio

if user.groups.filter(name='groupname').exists(): 
    # Action if existing 

else: 
    # Action if not existing 
1

Questo bit è probabilmente po 'troppo tardi (Ho appena aderito StackOverflow), ma per chiunque googling per all'inizio del 2018, puoi usare il fatto che l'oggetto Gruppi di Django (di default) ha i seguenti campi (non esaustivo, solo l'importazione ant uni):

id, nome, permessi, utente (può avere molti utenti; ManyToMany)

Nota che un gruppo può essere costituito da molti utenti, e un utente può essere un membro di molti gruppi. Così si può semplicemente filtrare il Django Gruppi modello per l'utente-sessione corrente (assicurarsi di aver aggiunto i gruppi interessati e assegnato all'utente di sua/il suo gruppo/s):

''' 
This assumes you have set up django auth properly to manage user logins 
''' 
# import Group models 
from django.contrib.auth.models import Group 

# filter the Group model for current logged in user instance 
query_set = Group.objects.filter(user = request.user) 

# print to console for debug/checking 
for g in query_set: 
    # this should print all group names for the user 
    print(g.name) # or id or whatever Group field that you want to display 
Problemi correlati