create group

Date: April 20th 2016
Last updated: April 20th 2016

Create group

# python3 manage.py shell
from django.contrib.auth.models import User, Group

new_group, created = Group.objects.get_or_create(name='new_group')
new_group

#<Group: new_group>

add user to a group

python3 manage.py shell
# get group
group = Group.objects.get(name='new_group')
# get user
u = User.objects.get(pk=2)
# add user to group
u.groups.add(group)

search all users in a group

# list all group members
group.user_set.all() # [<User: Ray>]

search groups that a user is in

u = User.objects.get(pk=2) 
u
#<User: Ray>
u.groups.all()
#[<Group: new_group>]

access groups in html template

views.py

@login_required
def groups(request):
    surfer_list = Surfer.objects.all()
    groups_list = Group.objects.all()
    context = {'surfer_list': surfer_list, 'groups_list': groups_list }
    return render(request, 'surferprofile/groups.html', context)

groups.html

<div style="margin: 5%;">
    <table>
        <tr>
            {% for group in groups_list %}
            {% if user in group.user_set.all %}
            <!-- 
            OR populate a table of group names if the user is not in the group 
            {% if user not in group.user_set.all %}
            -->
            <td>
                {{group.name}}
            </td>
            <td>
                members
            </td>
        </tr>
        {% endif %}
        {% endfor %}
    </table>
</div>

results matching ""

    No results matching ""