[Fixed]-Django get User Group in template

1👍

It seems you want to add a group to a user.
If that’s right, you can try below code

views.py

def Admin_add(request):
    if request.method == "POST":
        form = AdminSetup(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            group_name = request.POST.get('group_name')
            g = Group.objects.get(name=group_name)
            g.user_set.add(user)
            post.save()
            return redirect('admin_add.html', pk=post.pk)
    else:
        form = AdminSetup()
        groups = Group.objects.all()
    return render(request,'admin_add.html', {'form': form, 'groups': groups}, context_instance= RequestContext(request))

admin_add.html

<div class="form-group">
    <label>User Group</label>
        <select class="form-control">
            {% for group in groups %}
                <option name="group_name" value="{{ group.name }}">{{ group.name }}</option>
            {% endfor %}
        </select>
</div>

Leave a comment