let users delete groups

Date: April 22nd 2016
Last updated: April 22nd 2016

This example follows on from let users create their own groups. In this example I wanted to provide the Group creator the ability to delete their group. That is, they, and only they, can permanently remove the group. So this means that each Group has a unique permission assigned to different users.

I could not find a way to assign group permissions at an instance level. So, I ended up making a model that would hold this information. Once again, I'm not entirely sure this is the best way to go about it, but it works.

models.py
This is the table I created to hold Moderator information.

class GroupModerator(models.Model):
    group_user = models.ForeignKey(User)
    group_id = models.ForeignKey(Group)

update to views.py (creating groups)
The update is minimal but it serves to save the information of who is the group moderator.

@login_required
def add_group(request):
    surfer = get_object_or_404(Surfer, pk=request.user.surfer.id)
    if request.POST:
        form = AddGroupForm(data = request.POST)
        if form.is_valid():
            groupname = form.cleaned_data['name']
            new_group, created = Group.objects.get_or_create(name=groupname)
            u = User.objects.get(pk=request.user.id)
            u.groups.add(new_group)
            ############ UPDATES HERE ############
            # save user as moderator associated with a group 
            gm = GroupModerator(group_user = u, group_id = new_group)
            gm.save()
            ######################################
            return redirect('/groups')
    else:
        form = AddGroupForm()
    return render(request, 'surferprofile/addgroup.html',
                {'surfer': surfer, 'form': form})

html containing a button to delete a group

<!-- snipped - group.id comes from a forloop that is listing out all groups -->
<a href="{% url 'surferprofile:delete_group' my_group_id=group.id %}">
    <button style=""
          type="button"
          class="btn btn-primary">
          Delete group
    </button>
</a>
<!-- snipped -->

urls.py

from django.conf.urls import url
from . import views
app_name = 'surferprofile'
urlpatterns = [
    #<- snipped ->
    url(r'^deletegroup/(?P<my_group_id>[0-9]+)$', views.delete_group, name='delete_group'),
    ]

views.py (deleting groups)

login_required
def delete_group(request, my_group_id):
    group = get_object_or_404(Group, pk=my_group_id)
    gm = get_object_or_404(GroupModerator, group_id=my_group_id)
    if request.user.id == gm.group_user.id:
        group.delete()
    return redirect('/groups')

results matching ""

    No results matching ""