let users create their own groups

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

I should start off by saying that I am not sure this is the best way to acheive group creation for users. Nor am I sure that Django's Group model should be used this way. That said, what I have created does what I want. And that is, to allow each user to create as many groups as they want via a form, of which they instantly become a member.

html template containing an 'add group' button

<div class = 'container'>
    <div style="display:inline;">
        <h1>
            Community

        <a href="{% url 'surferprofile:add_group' %}">
              <button style="width: 180px; margin-left: 3%;"
                      type="button"
                      class="btn btn-primary">Add a group
               </button>
        </a>
        <button style="width: 100px; margin-left: 0%;"
                type="button"
                class="btn btn-success"
                onClick="javascript:history.go(-1);">
                Back
         </button>
    </h1>

urls.py

from django.conf.urls import url
from . import views

app_name = 'surferprofile'
urlpatterns = [
    #<- snipped ->
    url(r'^addgroup$', views.add_group, name='add_group'),
    #<- snipped ->
    ]

views.py

from .forms import AddGroupForm

@login_required
def add_group(request):
    # I am sending the surfer model through to the html as well
    # because I am using the surfer model as a failsafe to check that they
    # are authenticated to view the html.
    # Currently my authentication system is not strictly correct so I will
    # need to revisit this soon.
    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)
            return redirect('/groups')
    else:
        form = AddGroupForm()
    return render(request, 'surferprofile/addgroup.html',
                {'surfer': surfer, 'form': form})

forms.py
note I am using crispy forms, hence the stuff inside the __init__ function.

from django.contrib.auth.models import User, Group 

class AddGroupForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(AddGroupForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'post' # this line sets your form's method to post
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-4'
        self.helper.field_class = 'col-lg-6'
        self.helper.layout = Layout(
            'name',
            ButtonHolder(
                Submit('create', 'Create group', css_class='btn-primary')
            )
        )
    class Meta:
        model = Group
        fields = ['name']

addgroup.html
Actually now that I look at this... the authentication check is not required (ie. the line if user.id == surfer.user.id because the page is viewable by everyone and the group creation and addition is handled in views. I'll leave it as is for now.

{% extends 'surferprofile/base.html' %}
{% block title_block %} Add a group {% endblock %}
{% load crispy_forms_tags %}

{% block body_block %}

    <div id = "formcontainer">
        <h1 style="text-align: center;">Add group</h1>

    {% if user.id == surfer.user.id %}

        <form id='addgroup' role="form" action="" method="post" style="text-align: right;">
            {% csrf_token %}
            {% crispy form %}
        </form>
    </div>

    {% else %}
        <p> You can not edit this profile </p>
        <p>user.id ={{ user.id}}</p>
        <p>surfer.user.id = {{ surfer.user.id}}</p>

{% endif %}

{% endblock %}

html form

results matching ""

    No results matching ""