Exemple #1
0
def edit_group(grupo):
	# grupo = Grupo.objects.get_or_404(nombre=grupo)
	grupo = Grupo.objects.get_or_create(nombre=grupo,defaults={'horario': 'Sin definir'})
	grupo_id=grupo[0].id
	# if len(grupo[0].horario)<1:
	# 	grupo[0].horario = 'Sin definir'
	# user_json=usuario
	# uuu = [{'nombre':'nombre','username':'******'}]
	# post = Usuario.objects.get_or_404(username=username)
	form = GroupForm(request.form,grupo[0])
	if request.method == 'POST':
		if form.validate() == False:
			flash('Todos los campos son necesarios.')
			return render_template('usuarios/groups.html', form=form, data_type="Grupos", action="Editar")
		else:
			# flash('Valores por defecto.')
			g=Grupo.objects.get(id=grupo_id)
			g.update(set__nombre=form.nombre.data)
			g.update(set__horario=form.horario.data)
			# grupo[0].nombre=form.nombre.data
			# grupo[0].horario=form.horario.data
			# grupo[0].save()
			# return render_template('usuarios/groups.html', form=form, data_type="Grupos", action="Editar")
			grupos = Grupo.objects.all()
			return render_template ('usuarios/groups.html', grupos=grupos, action="Listar")
			# return render_template('grupos.html')
 
	elif request.method == 'GET':
		return render_template('usuarios/groups.html', form=form, data_type="Grupos", action="Editar")
Exemple #2
0
def group_create(request):
    """
    create a form a user can use to create a custom group, on POST save this group to the database
    and automatically add the creator to the said group as a manager.
    """
    nav_selected = "communities"
    if request.method == "POST":
        form = GroupForm(request.POST, request.FILES)
        if form.is_valid():
            group = form.save()
            GroupUsers.objects.create(group=group, user=request.user, is_manager=True)
            Stream.objects.get(slug="community-create").enqueue(content_object=group, start=group.created)
            Record.objects.create_record(request.user, 'group_create', group)
            badge_cache.possibly_award_badge('created_a_community', user=request.user)
            messages.success(request, _("%(group)s has been created.") % {
                    'group': group})
            return redirect("group_detail", group_slug=group.slug)
    else:
        form = GroupForm()
    return render_to_response("groups/group_create.html", {
        "form": form,
        "site": Site.objects.get_current(),
        "nav_selected": nav_selected,
        'external_group': False,
    }, context_instance=RequestContext(request))
Exemple #3
0
def edit_group(request, id):
    group = get_object_or_404(Group, id=id)
    try:
        group_title = models.GroupTitle.objects.get(group=group)
    except models.GroupTitle.DoesNotExist:
        group_title = None

    if request.method == 'POST':
        form = GroupForm(request.POST, instance=group)
        group_title_form = GroupTitleForm(request.POST, prefix='gtf', instance=group_title)
        if form.is_valid() and group_title_form.is_valid():
            group = form.save(commit=False)

            if form.cleaned_data['permissions']:
                group.permissions = form.cleaned_data['permissions']
            else:
                group.permissions.clear()

            group.save()

            if not group_title:
                group_title = group_title_form.save(commit=False)
                group_title.group = group
                group_title.save()
            else:
                group_title_form.save()
            return redirect('accounts:administration:groups_list')
    else:
        form = GroupForm(instance=group)
        group_title_form = GroupTitleForm(prefix='gtf', instance=group_title)
    return render(request, 'accounts/administration/edit_group.html', {
        'form': form,
        'group_title_form': group_title_form
    })
Exemple #4
0
def new_group(request):
    if request.method == 'POST':
        form = GroupForm(request.POST)
        if form.is_valid():
            group_code = helper.post_request("https://a6.cfapps.io/groups", {})
            groupID = json.loads(group_code)['groupId']
            group = Group.objects.create(code=groupID, name=form.cleaned_data['name'])
            group.save()
            #Create a new subscription for group
            url = "https://a6.cfapps.io/subscriptions"
            payload = {}
            payload['groupId'] = group.code
            payload['insights'] = [
                "home.window.open",
                "home.window.closed",
                "home.garage.open",
                "home.garage.closed",
                "home.smoke.alarm_on",
                "home.smoke.alarm_off",
                "home.smoke.alarm_battery_low",
                "home.fire.alarm_on",
                "home.fire.alarm_off",
                "home.water.sensor.alarm_on",
                "home.water.sensor.alarm_off",
                "vehicle.trip.arrived",
                "vehicle.health.arrived"]
            payload['webhookUrl'] = 'https://homesensing.cfapps.io/callback'
            result = helper.post_request(url, payload)
            print result
            return HttpResponseRedirect("/index")
    else:
        form = GroupForm()
    return render_to_response('new_group.html', { 'form' : form }, context_instance=RequestContext(request))
def addGroup():

  if 'email' not in session:
    return redirect(url_for('signin'))

  user = Smarketer.query.filter_by(username = session['email']).first()

  if user is None:
    return redirect(url_for('signin'))
  else:
    form = GroupForm()

    if request.method == 'POST':
      if form.validate() == False:
        return render_template('addGroup.html', form=form)
      else:
	totalTitle = form.groupTitle.data + " - " + form.groupID.data
        newGroup = Group(form.groupID.data, totalTitle)
        db.session.add(newGroup)
        db.session.commit()

	form.groupID.data = ""
	form.groupTitle.data = ""
        return render_template('addGroup.html', form=form, success=True)

    elif request.method == 'GET':
      return render_template('addGroup.html', form=form)
Exemple #6
0
def groups(group_id=None):
    form = GroupForm(request.form)
    if request.method == 'POST':
        if not form.validate():
            pass
        else:
            pass
    return render_template('groups.html', user=get_user(), form=form)
Exemple #7
0
def create_group(request):
    if request.method == 'POST':
        form = GroupForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('accounts:administration:groups_list')
    else:
        form = GroupForm()
    return render(request, 'accounts/administration/create_group.html', {
        'form': form
    })
Exemple #8
0
def save_new_group(request):

    if request.method == 'POST':
        form = GroupForm(request.POST)
        if form.is_valid():
            group = Group()
            group.name = form.cleaned_data['name']
            group.max_loan_days = form.cleaned_data['max_loan_days']
            group.save()

    return HttpResponseRedirect('/webconf/couchauth/')
Exemple #9
0
def save_new_group(request):

    if request.method == 'POST':

        form = GroupForm(request.POST)
        if form.is_valid():

            group = Group()
            group.name = form.cleaned_data['name']
            group.save()

    return HttpResponseRedirect('/webconf/aclsmanager/show_groups/')
Exemple #10
0
def add_group(request):
    
    if request.method == 'POST':
        groupForm = GroupForm(request.POST)
        if groupForm.is_valid():
            group = groupForm.save()
            request.user.message_set.create(message=_('Group created'))
            return redirect('picket-admin-users')
    else:
        groupForm = GroupForm()
    
    return direct_to_template(request, 'picket/admin/group_add.html',
        {'group_form': groupForm,})
Exemple #11
0
def save_group(request, group_id):
    try:
        group = Group.objects.get(id=group_id)
    except Group.DoesNotExist:
        return HttpResponseRedirect('/webconf/aclsmanager/show_groups/')

    if request.method == 'POST':
        form = GroupForm(request.POST)
        if form.is_valid():
            group.name = form.cleaned_data['name']
            group.save()

    return HttpResponseRedirect('/webconf/aclsmanager/show_groups/')
Exemple #12
0
def groups():
    form = GroupForm()
    if form.validate_on_submit():
        group_id = form.id.data
        if group_id:
            group = models.Group.query.get(group_id)
            group.name = form.name.data
        else:
            group = models.Group(name=form.name.data)
            db.session.add(group)
        db.session.commit()
        flash('The group was successffully saved.', 'success')
        return redirect(url_for('groups'))
    groups = models.Group.query.all()
    return render_template('groups.html', form=form, groups=groups)
Exemple #13
0
def add_group(request):
    context = {}

    if request.method == "POST":
        form = GroupForm(request.POST)
        if form.is_valid():
            group = form.save(commit=False)
            group.added_by = request.user
            group.save()
            return HttpResponseRedirect("/group/%s" % group.id)
    else:
        form = GroupForm()

    context["form"] = form
    return r2r(request, "add_group", context)
Exemple #14
0
def edit_group(request, groupId):
    
    group = get_object_or_404(Group, id=groupId)
    
    if request.method == 'POST':
        groupForm = GroupForm(request.POST, instance=group)
        if groupForm.is_valid():
            group = groupForm.save()
            request.user.message_set.create(message=_('Group updated'))
            return redirect('picket-admin-users')
    else:
        groupForm = GroupForm(instance=group)
    
    return direct_to_template(request, 'picket/admin/group_edit.html',
        {'group_form': groupForm,})
Exemple #15
0
def group_add(request):
    temp_name = "cmdb/cmdb-header.html"
    if request.method == "POST":
        group_form = GroupForm(request.POST)
        if group_form.is_valid():
            group_form.save()
            tips = u"增加成功!"
            display_control = ""
        else:
            tips = u"增加失败!"
            display_control = ""
        return render(request, "cmdb/group_base.html", locals())
    else:
        display_control = "none"
        group_form = GroupForm()
        return render(request, "cmdb/group_base.html", locals())
Exemple #16
0
def edit_group(request, group_id):
    context = {}
    group = Group.objects.get(pk=group_id)

    if not request.user.is_staff and request.user.email != group.added_by.email:
        return HttpResponseRedirect("/group/%s" % group_id)

    if request.method == "POST":
        form = GroupForm(request.POST, instance=group)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/group/%s" % group_id)
    else:
        form = GroupForm(instance=group)

    context["form"] = form
    return r2r(request, "edit_group", context)
Exemple #17
0
 def post(self, request, format=None, *args, **kwargs):
     if format == 'html' or format == None:
         form = GroupForm(request.POST)
         if form.is_valid():
             group = form.save(commit=False)
             group.creator = request.user
             group.save()
             group.members.add(request.user)
             group.save()
             return redirect('/groups/' + str(group.id))
     elif format == 'json':
         serializer = GroupSerializer(data=request.DATA)
         if serializer.is_valid():
             serializer.save()
             return Response(serializer.data, status=status.HTTP_201_CREATED)
         else:
             return Response(serializer.errors)
Exemple #18
0
def edit_group(request, group_id):
    projects = Project.objects.all()
    print(request.POST)
    try:
        group = ReportGroup.objects.get(pk=group_id)
    except Exception as e:
        print("Exception: " + str(e))
    try:
        members = GroupMember.objects.filter(group=group)
    except Exception as e:
        print("Exception: " + str(e))
    try:
        users = User.objects.all()
        user_list = []
        for user in users:
            keep = True
            for member in members:
                if member.user == user:
                    keep = False
            if keep:
                user_list.append(user)

    except Exception as e:
        print("Exception: " + str(e))
    if request.method == 'POST':
        try:
            form = GroupForm(request.POST, instance=group)
            added_members = request.POST.getlist('new_members')
            removed_members = request.POST.getlist('del_members')
            if form.is_valid():
                group = form.save()
                for member in added_members:
                    temp = User.objects.get(pk=member)
                    new_member = GroupMember(group=group, user=temp)
                    new_member.save()
                for member in removed_members:
                    temp = User.objects.get(pk=member)
                    old_member = GroupMember.objects.get(user=temp, group=group)
                    old_member.delete()
                return redirect('daily_reports.views.request_report_summary')
        except Exception as e:
            print(e)
    else:
        form = GroupForm(instance=group)
    return render_to_response('daily_reports/edit_report_group.html', {'members': members, 'users': user_list, 'form': form, 'projects': projects, 'group': group}, context_instance=RequestContext(request))
Exemple #19
0
def save_group(request, group_id):
    if request.method == 'POST':
        form = GroupForm(request.POST)
        if form.is_valid():

            try:
                group = Group.get(group_id)
            except:
                return HttpResponseRedirect('/webconf/couchauth/show_groups/')

            users = request.POST.getlist('users')
            group.update_users(users)
            if group.name != form.cleaned_data['name']:
                group.name = form.cleaned_data['name']
                group.save()


    return HttpResponseRedirect('/webconf/couchauth/show_groups/')
Exemple #20
0
def create_group(request):
    if request.method == 'POST':
        form = GroupForm(request.POST)
        group_title_form = GroupTitleForm(request.POST, prefix='gtf')
        if form.is_valid() and group_title_form.is_valid():
            group = form.save(commit=False)
            group.save()
            group_title = group_title_form.save(commit=False)
            group_title.group = group
            group_title.save()
            return redirect('accounts:administration:groups_list')
    else:
        form = GroupForm()
        group_title_form = GroupTitleForm(prefix='gtf')
    return render(request, 'accounts/administration/create_group.html', {
        'form': form,
        'group_title_form': group_title_form
    })
Exemple #21
0
def group_add(request, response_format='html'):
    "Group add"

    if request.POST:
        if 'cancel' not in request.POST:
            form = GroupForm(request.POST)
            if form.is_valid():
                group = form.save()
                return HttpResponseRedirect(reverse('core_admin_group_view', args=[group.id]))
        else:
            return HttpResponseRedirect(reverse('core_admin_index_groups'))

    else:
        form = GroupForm()

    return render_to_response('core/administration/group_add',
                              {'form': form},
                              context_instance=RequestContext(request), response_format=response_format)
Exemple #22
0
def group_edit(request, group_id):
    project = HostGroup.objects.get(id=group_id)
    temp_name = "cmdb/cmdb-header.html"
    if request.method == 'POST':
        form = GroupForm(request.POST, instance=project)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('group'))
    else:
        form = GroupForm(instance=project)
    display_control = "none"
    results = {
        'group_form': form,
        'group_id': group_id,
        'request': request,
        'temp_name': temp_name,
        'display_control': display_control,
    }
    return render(request, 'cmdb/group_base.html', results)
def set_organization_group(request, org_url, group_role=""):
    organization = request.organization
    #get or create revelant organization group
    try:
        organizationgroup = OrganizationGroup.objects.filter(
            role__exact=group_role,
            org=organization)[0]
    except IndexError:
        organizationgroup = None

    if not organizationgroup:
        role_name = dict(OrganizationGroup.GROUP_ROLES)[group_role]
        group_name = u"%s %s" % (organization.name, role_name)
        group = Group.objects.get_or_create(name=group_name)
        organizationgroup = OrganizationGroup.objects.create(
            role=group_role,
            group=group[0],
            org=organization)

    form = GroupForm(
        request.POST or None,
        instance=organizationgroup.group)
    form.fields["users"].queryset = organization.staff_group.user_set.all()

    if form.is_valid():
        group = form.save()
        # store reference to group in organization
        setattr(organization, group_role, group)
        organization.save()
        return redirect("organization", (org_url,))

    return render(
        request,
        "organizations/edit_group.html",
        dict(
            form=form,
            org=organization,
            group=organizationgroup.group,
            group_types=organizationgroup.GROUP_ROLES,
            org_url=org_url
        ),
    )
Exemple #24
0
def group_edit(request, group_id, response_format='html'):
    "Group edit"

    group = get_object_or_404(Group, pk=group_id)

    if request.POST:
        if 'cancel' not in request.POST:
            form = GroupForm(request.POST, instance=group)
            if form.is_valid():
                group = form.save()
                return HttpResponseRedirect(reverse('core_admin_group_view', args=[group.id]))
        else:
            return HttpResponseRedirect(reverse('core_admin_group_view', args=[group.id]))
    else:
        form = GroupForm(instance=group)

    return render_to_response('core/administration/group_edit',
                              {'group': group,
                               'form': form},
                              context_instance=RequestContext(request), response_format=response_format)
Exemple #25
0
def create_group():
    if g.user.max_groups():
        flash(gettext('How many groups do you need to be in? Only 5 for you :)'))
        return redirect(url_for('index'))
    form = GroupForm()
    if form.validate_on_submit():
        group = Group(group_name = form.group_name.data,
            about_group = form.about_group.data,
            public = form.public.data)
        db.session.add(group)
        db.session.commit()
        # Create group, add creator to admin and user list.
        db.session.add(group.add_admin(g.user))
        db.session.add(group.add_user(g.user))
        db.session.commit()
        flash('Welcome to your new group!  Now add some friends!')
        return redirect(url_for('group', group_id = group.id))
    return render_template('group_form.html',
        title = 'Create Group',
        form = form)
Exemple #26
0
def edit_group(request, id):
    group = get_object_or_404(Group, id=id)
    if request.method == 'POST':
        form = GroupForm(request.POST, instance=group)
        if form.is_valid():
            group = form.save(commit=False)

            if form.cleaned_data['permissions']:
                group.permissions = form.cleaned_data['permissions']
            else:
                group.permissions.clear()

            group.save()
            return redirect('accounts:administration:groups_list')
    else:
        form = GroupForm(instance=group)

    return render(request, 'accounts/administration/edit_group.html', {
        'form': form
    })
Exemple #27
0
def setup_report_group(request):
    projects = Project.objects.all()
    users = User.objects.all()
    if request.method == 'POST':
        try:
            group = ReportGroup()
            form = GroupForm(request.POST, instance=group)
            members = request.POST.getlist('users')
            if form.is_valid():
                group = form.save()
                for member in members:
                    temp = User.objects.get(username=member)
                    new_member = GroupMember(group=group, user=temp)
                    new_member.save()
                return redirect('daily_reports.views.request_report_summary')
        except Exception as e:
            print("Exception: " + str(e))
    else:
        form = GroupForm()
    return render_to_response('daily_reports/report_group_form.html', {'users': users, 'projects': projects, 'form': form}, context_instance=RequestContext(request))
Exemple #28
0
def add_group():
    """
    Add a group to the database.
    :return:
    """
    check_admin()
    form = GroupForm()
    if form.validate_on_submit():
        group = Group(name=form.name.data, description=form.description.data)
        try:
            db.session.add(group)
            db.session.commit()
            flash('Successfully added a new group: "%s".' % str(group.name))
        except:
            db.session.rollback()
            flash('Failed to add the group: "%s".' % str(group.name))
        return redirect(url_for('admin.groups'))
    return render_template('admin/groups/add_group.html',
                           title='Add Group',
                           action='Add',
                           form=form)
Exemple #29
0
def titleSettingViews(request):
    """
    JunHU
    """
    user_id = request.GET.get("user_id")
    user = User.objects.get(id=user_id)
    group_form = GroupForm(request=request)
    context = {
        "setting_user": user,
        "group_form": group_form,
    }
    return render(request, "management/title_setting.html", context)
def group_create(request):
    """
    create a form a user can use to create a custom group, on POST save this group to the database
    and automatically add the creator to the said group as a manager.
    """
    nav_selected = "communities"
    if request.method == "POST":
        form = GroupForm(request.POST, request.FILES)
        if form.is_valid():
            group = form.save()
            GroupUsers.objects.create(group=group,
                                      user=request.user,
                                      is_manager=True)
            Stream.objects.get(slug="community-create").enqueue(
                content_object=group, start=group.created)
            Record.objects.create_record(request.user, 'group_create', group)
            badge_cache.possibly_award_badge('created_a_community',
                                             user=request.user)
            messages.success(request, "%s has been created." % group)
            return redirect("group_detail", group_slug=group.slug)
    else:
        form = GroupForm()
    return render_to_response("groups/group_create.html", {
        "form": form,
        "site": Site.objects.get_current(),
        "nav_selected": nav_selected
    },
                              context_instance=RequestContext(request))
Exemple #31
0
def group_edit(request, group_slug):
    nav_selected = "communities"
    group = get_object_or_404(Group, slug=group_slug, is_geo_group=False)
    if not group.is_user_manager(request.user):
        return forbidden(request)

    if group.is_external_link_only:
        return _group_external_link_only_edit(request, group)

    external_group = False
    if request.method == "POST":
        if "change_group" in request.POST:
            group_form = GroupForm(request.POST, request.FILES, instance=group)
            if group_form.is_valid():
                group = group_form.save()
                messages.success(request, _("%(group)s has been updated.") % {'group': group})
                return redirect("group_edit", group_slug=group.slug)
            else:
                membership_form = MembershipForm(group=group)
                discussions_form = DiscussionSettingsForm(instance=group)
        if "discussion_settings" in request.POST:
            discussions_form = DiscussionSettingsForm(request.POST, instance=group)
            if discussions_form.is_valid():
                group = discussions_form.save()
                messages.success(request, _("%(group)s has been updated.") % {'group': group})
                return redirect("group_edit", group_slug=group.slug)
            else:
                membership_form = MembershipForm(group=group)
                group_form = GroupForm(instance=group)
        elif "delete_group" in request.POST:
            group.delete()
            messages.success(request, _("%(group)s has been deleted.") % {'group': group})
            return redirect("group_list")
        elif "change_membership" in request.POST:
            membership_form = MembershipForm(group=group, data=request.POST)
            if membership_form.is_valid():
                membership_form.save()
                if group.is_user_manager(request.user):
                    messages.success(request, _("%(group)s's memberships have been updated.") % {
                            'group': group})
                    return render_to_response("groups/group_edit.html", locals(), 
                                              context_instance=RequestContext(request))
                else:
                    messages.success(request,
                                     _("You no longer have permissions to edit %(group)s") % {
                                'group': group})
                    return redirect("group_detail", group_slug=group.slug)
            else:
                group_form = GroupForm(instance=group)
                discussions_form = DiscussionSettingsForm(instance=group)
        else:
            messages.error(request, _("No action specified."))
    else:
        group_form = GroupForm(instance=group)
        membership_form = MembershipForm(group=group)
        discussions_form = DiscussionSettingsForm(instance=group)
    site = Site.objects.get_current()
    requesters = group.requesters_to_grant_or_deny(request.user)
    return render_to_response("groups/group_edit.html", locals(), 
                              context_instance=RequestContext(request))
Exemple #32
0
def show_group(request, group_id):
    try:
        group = Group.get(group_id)
    except:
        return HttpResponseRedirect('/webconf/couchauth/show_groups/')

    form = GroupForm(instance=group)
    if form.is_valid():
        group = Group()
        group.name = form.cleaned_data['name']
        group.max_loan_days = form.cleaned_data['max_loan_days']
        group.save()
    form_url = "/webconf/couchauth/save_group/%s/" % group_id
    context = { 'form': form,
                'form_title': 'Editar Grupo',
                'group': group,
                'form_url': form_url,
                }
    return render_to_response('webconf/couchauth/form_group.html',
                              context,
                              context_instance=RequestContext(request)
                              )
Exemple #33
0
def show_group(request, group_id):
    try:
        group = Group.get(group_id)
    except:
        return HttpResponseRedirect('/webconf/couchauth/show_groups/')

    form = GroupForm(instance=group)
    if form.is_valid():
        group = Group()
        group.name = form.cleaned_data['name']
        group.max_loan_days = form.cleaned_data['max_loan_days']
        group.save()
    form_url = "/webconf/couchauth/save_group/%s/" % group_id
    context = {
        'form': form,
        'form_title': 'Editar Grupo',
        'group': group,
        'form_url': form_url,
    }
    return render_to_response('webconf/couchauth/form_group.html',
                              context,
                              context_instance=RequestContext(request))
Exemple #34
0
def	TmcData6(request):


    if CheckAccess(request,'2') != 'OK':
	return render_to_response("tmc/notaccess/tmc.html")


    ## --- Номер заявки ---
    try:
	tmc_id = request.GET['tmc_id']
	request.session['tmc_id'] = tmc_id
    except:
	pass

    try:
	tmc_id = request.session['tmc_id']
    except:
	return HttpResponseRedirect("/tmc")


    if request.method == 'POST':
	form = GroupForm(request.POST)
	if form.is_valid():
	    comment = form.cleaned_data['comment']
	    group = form.cleaned_data['group']
	    ChangeTmcGroup(GetUserKod(request),tmc_id,comment,group)



    d = GetTmcData(tmc_id)
    data = GetGroupHistory(tmc_id)

    form = GroupForm(None)

    s =GetLastStatus(tmc_id)

    c = RequestContext(request,{'d':d,'form':form,'data':data,'s':s})
    c.update(csrf(request))
    return render_to_response("tmc/tmcdata6.html",c)
Exemple #35
0
def new_group(request):
    form = GroupForm()
    users = User.view("couchauth/all_users")
    form_url = "/webconf/couchauth/save_new_group/"
    context = {
        'form': form,
        'form_url': form_url,
        'form_title': 'Crear Grupo',
        'users': users,
    }
    return render_to_response('webconf/couchauth/form_group.html',
                              context,
                              context_instance=RequestContext(request))
    def create_form(self, resource=None, edit_form=False):
        """Return form with fields loaded from DB.

        :param object resource: Optional group object
        :param bool edit_form: Set if edit form
        """
        form = GroupForm(self.config_models, obj=resource)

        session = self.session()
        self.update_form_users(resource, edit_form, form, session)
        self.update_form_roles(resource, edit_form, form, session)
        session.close()

        return form
Exemple #37
0
def group_modify(request, group_id):
    group_obj = Group.objects.get(id=group_id)
    form = GroupForm(instance=group_obj)
    if request.method == "POST":
        form = GroupForm(request.POST, instance=group_obj)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.SUCCESS, u'信息修改成功')
            return HttpResponseRedirect(reverse('group_list'))
    return render_to_response("core/group_modify.html", {
        'form': form,
    },
                              context_instance=RequestContext(request))
Exemple #38
0
def show_group(request, group_id):
    try:
        group = Group.objects.get(id=group_id)
    except Group.DoesNotExist:
        return HttpResponseRedirect('/webconf/aclsmanager/show_groups/')
    form = GroupForm(instance=group)
    form_url = "/webconf/aclsmanager/save_group/%s/" % group_id
    context = {
        'form': form,
        'group': group,
        'form_url': form_url,
    }
    return render_to_response('webconf/aclsmanager/form_acls.html',
                              context,
                              context_instance=RequestContext(request))
Exemple #39
0
 def getEditFormContext():
     group = conn.getObject("ExperimenterGroup", gid)
     ownerIds = [e.id for e in group.getOwners()]
     memberIds = [m.id for m in group.getMembers()]
     permissions = getActualPermissions(group)
     form = GroupForm(
         initial={
             'name': group.name,
             'description': group.description,
             'permissions': permissions,
             'owners': ownerIds,
             'members': memberIds,
             'experimenters': experimenters,
         })
     return {'form': form, 'gid': gid, 'permissions': permissions}
Exemple #40
0
def user_followed_groups(req, student_username):
    """
    :param req: the received HTTP request
    :param student_username: user name of the student whose followed groups are requested
    :return: render of group cards of all followed groups
    """
    user = User.objects.filter(username=student_username)[0]
    new_group_form = GroupForm()
    context = {
        "groups": user.student.groups_followed.all(),
        "form": new_group_form,
        "student": user,
        "action": "create"
    }
    return render(req, 'mines_book/group_cards.html', context)
    def create_form(self, resource=None, edit_form=False):
        """Return form with fields loaded from DB.

        :param object resource: Optional group object
        :param bool edit_form: Set if edit form
        """
        form = GroupForm(self.config_models, obj=resource)

        session = self.session()
        self.update_form_collection(resource, edit_form, form.users, self.User,
                                    'sorted_users', 'id', 'name', session)
        self.update_form_collection(resource, edit_form, form.roles, self.Role,
                                    'sorted_roles', 'id', 'name', session)
        session.close()

        return form
Exemple #42
0
def group_add(request):
    form = GroupForm()
    if request.method == "POST":
        form = GroupForm(request.POST)
        if form.is_valid():
            form.save()

            # 为新用户分配发送池
            messages.add_message(request, messages.SUCCESS, u'信息添加成功')
            return HttpResponseRedirect(reverse('group_list'))
    return render_to_response("core/group_modify.html", {
        'form': form,
    },
                              context_instance=RequestContext(request))
Exemple #43
0
def create_group(request):
    """ Create a new group. """
    group_form = GroupForm()
    if request.method == "POST":
        group_form = GroupForm(request.POST)
        if group_form.is_valid():
            group = group_form.save(commit=False)
            group.owner = request.user
            group.save()
            messages.success(request, "%s added" % group.name)
            return redirect("view_group", group.id)
    return render(request, "contacts/groups/create.html", {"form": group_form})
Exemple #44
0
def group_add(request):
    temp_name = "cmdb/cmdb-header.html"
    if request.method == "POST":
        group_form = GroupForm(request.POST)
        if group_form.is_valid():
            group_form.save()
            tips = u"增加成功!"
            display_control = ""
        else:
            tips = u"增加失败!"
            display_control = ""
        return render(request, "cmdb/group_base.html", locals())
    else:
        display_control = "none"
        group_form = GroupForm()
        return render(request, "cmdb/group_base.html", locals())
Exemple #45
0
def edit_group(request, group_id):
    context = {}
    group = Group.objects.get(pk=group_id)

    if not request.user.is_staff and request.user.email != group.added_by.email:
        return HttpResponseRedirect("/group/%s" % group_id)

    if request.method == "POST":
        form = GroupForm(request.POST, instance=group)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/group/%s" % group_id)
    else:
        form = GroupForm(instance=group)

    context["form"] = form
    return r2r(request, "edit_group", context)
Exemple #46
0
def edit_group(request, pk):
    """ Edit a group. """
    group = get_object_or_404(Group, pk=pk, owner=request.user)
    group_form = GroupForm(instance=group)
    if request.method == "POST":
        group_form = GroupForm(request.POST, instance=group)
        if group_form.is_valid():
            group = group_form.save()
            messages.success(request, "%s updated" % group.name)
            return redirect("view_group", group.id)
    return render(request, "contacts/groups/edit.html", {
        "group": group,
        "form": group_form
    })
Exemple #47
0
def add_group(request):
    context = {}

    if request.method == "POST":
        form = GroupForm(request.POST)
        if form.is_valid():
            group = form.save(commit=False)
            group.added_by = request.user
            group.save()
            return HttpResponseRedirect("/group/%s" % group.id)
    else:
        form = GroupForm()

    context["form"] = form
    return r2r(request, "add_group", context)
Exemple #48
0
def group_edit(request, group_id):
    project = HostGroup.objects.get(id=group_id)
    temp_name = "cmdb/cmdb-header.html"
    if request.method == 'POST':
        form = GroupForm(request.POST, instance=project)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('group'))
    else:
        form = GroupForm(instance=project)
    display_control = "none"
    results = {
        'group_form': form,
        'group_id': group_id,
        'request': request,
        'temp_name': temp_name,
        'display_control': display_control,
    }
    return render(request, 'cmdb/group_base.html', results)
Exemple #49
0
def group_add_mini(request):
    temp_name = "cmdb/cmdb-header.html"
    if request.method == "POST":
        group_form = GroupForm(request.POST)
        if group_form.is_valid():
            group_form.save()
            tips = u"增加成功!"
            display_control = ""
            status = 1
        else:
            tips = u"增加失败!"
            display_control = ""
        return render_to_response("cmdb/group_add_mini.html", locals(),
                                  RequestContext(request))
    else:
        display_control = "none"
        group_form = GroupForm()
        return render_to_response("cmdb/group_add_mini.html", locals(),
                                  RequestContext(request))
Exemple #50
0
 def getEditFormContext():
     group = conn.getObject("ExperimenterGroup", gid)
     ownerIds = [e.id for e in group.getOwners()]
     memberIds = [m.id for m in group.getMembers()]
     permissions = getActualPermissions(group)
     system_groups = [conn.getAdminService().getSecurityRoles().systemGroupId,
                      conn.getAdminService().getSecurityRoles().userGroupId,
                      conn.getAdminService().getSecurityRoles().guestGroupId]
     group_is_current_or_system = (conn.getEventContext().groupId == long(gid)) or (long(gid) in system_groups)
     form = GroupForm(initial={
         'name': group.name,
         'description':group.description,
         'permissions': permissions, 
         'owners': ownerIds,
         'members':memberIds,
         'experimenters':experimenters},
         group_is_current_or_system=group_is_current_or_system)
     admins = [conn.getAdminService().getSecurityRoles().rootId]
     if long(gid) in system_groups:
         # prevent removing 'root' or yourself from group if it's a system group
         admins.append(conn.getUserId())
     return {'form':form, 'gid': gid, 'permissions': permissions, "admins": admins}
Exemple #51
0
def create_group(request):
    if request.method == 'POST':
        form = GroupForm(request.POST)
        group_title_form = GroupTitleForm(request.POST, prefix='gtf')
        if form.is_valid() and group_title_form.is_valid():
            group = form.save(commit=False)
            group.save()
            group_title = group_title_form.save(commit=False)
            group_title.group = group
            group_title.save()
            return redirect('accounts:administration:groups_list')
    else:
        form = GroupForm()
        group_title_form = GroupTitleForm(prefix='gtf')
    return render(request, 'accounts/administration/create_group.html', {
        'form': form,
        'group_title_form': group_title_form
    })
Exemple #52
0
def group_add(request, template_name='accounts/group_add.html'):
    permission_list = Permission.objects.all()
    username = request.session['username']
    permission = 'auth.add_group'
    if current_user_permissions(username, permission):
        if request.method == 'POST':
            form = GroupForm(request.POST, request.FILES)
            if form.is_valid():
                print form
                group = form.save(commit=False)
                group.save()
            return redirect('group_list')
        else:
            form = GroupForm()
        return render(
            request, template_name, {
                'form': form,
                'username': username,
                'var2': 'active',
                'highlight1': 'active',
                'permission_list': permission_list
            })
    else:
        return HttpResponse("权限不够")
Exemple #53
0
def edit_group(request, id):
    group = get_object_or_404(Group, id=id)
    try:
        group_title = models.GroupTitle.objects.get(group=group)
    except models.GroupTitle.DoesNotExist:
        group_title = None

    if request.method == 'POST':
        form = GroupForm(request.POST, instance=group)
        group_title_form = GroupTitleForm(request.POST,
                                          prefix='gtf',
                                          instance=group_title)
        if form.is_valid() and group_title_form.is_valid():
            group = form.save(commit=False)

            if form.cleaned_data['permissions']:
                group.permissions = form.cleaned_data['permissions']
            else:
                group.permissions.clear()

            group.save()

            if not group_title:
                group_title = group_title_form.save(commit=False)
                group_title.group = group
                group_title.save()
            else:
                group_title_form.save()
            return redirect('accounts:administration:groups_list')
    else:
        form = GroupForm(instance=group)
        group_title_form = GroupTitleForm(prefix='gtf', instance=group_title)
    return render(request, 'accounts/administration/edit_group.html', {
        'form': form,
        'group_title_form': group_title_form
    })
Exemple #54
0
def admin():
    role_form = RoleForm()
    users = User.query.all()
    usernames = [u.username for u in users]
    role_form.username.validators.append(
        AnyOf(usernames, message="Username not found."))
    if role_form.validate_on_submit():
        form = role_form
        user = User.query.filter(User.username == form.username.data).one()

        try:
            role = Role.query.filter(Role.name == form.role.data).one()
        except NoResultFound:
            role = Role(name=form.role.data)
            db.session.add(role)

        if form.action.data == "add":
            if role not in user.roles:
                user.roles.append(role)
                db.session.add(user)
        elif form.action.data == "remove":
            if role in user.roles:
                user.roles.remove(role)
                db.session.add(user)

        db.session.commit()
        return redirect(url_for("horti.admin"))

    group_form = GroupForm()
    if group_form.validate_on_submit():
        form = group_form
        name = form.name.data
        if form.action.data == "add":
            tweety.post_groups(name=name)
        elif form.action.data == "remove":
            tweety.delete_group(name)
        groups = cache(tweety.get_groups, force_refresh=True)
        return redirect(url_for("horti.admin"))

    # display groups
    have_groups = False
    while not have_groups:
        groups = cache(tweety.get_groups)
        if not isinstance(groups, Response):
            have_groups = True
            groups.sort()
        sleep(0.2)

    # display roles
    roles = {}
    for user in users:
        roles[user.username] = ", ".join(sorted([r.name for r in user.roles]))

    template_data = {
        "role_form": role_form,
        "users": users,
        "roles": roles,
        "groups": groups,
        "group_form": group_form
    }
    return render_template("admin.html",
                           title=make_title("Admin"),
                           **template_data)
Exemple #55
0
def manage_group(request, action, gid=None, conn=None, **kwargs):
    template = "webadmin/group_form.html"

    experimenters = list(conn.getObjects("Experimenter"))

    if action == 'new':
        form = GroupForm(initial={
            'experimenters': experimenters,
            'permissions': 0
        })
        context = {'form': form}
    elif action == 'create':
        if request.method != 'POST':
            return HttpResponseRedirect(
                reverse(viewname="wamanagegroupid", args=["new"]))
        else:
            name_check = conn.checkGroupName(request.REQUEST.get('name'))
            form = GroupForm(initial={'experimenters': experimenters},
                             data=request.POST.copy(),
                             name_check=name_check)
            if form.is_valid():
                logger.debug("Create group form:" + str(form.cleaned_data))
                name = form.cleaned_data['name']
                description = form.cleaned_data['description']
                owners = form.cleaned_data['owners']
                members = form.cleaned_data['members']
                permissions = form.cleaned_data['permissions']

                perm = setActualPermissions(permissions)
                listOfOwners = getSelectedExperimenters(conn, owners)
                gid = conn.createGroup(name, perm, listOfOwners, description)
                new_members = getSelectedExperimenters(
                    conn, mergeLists(members, owners))
                group = conn.getObject("ExperimenterGroup", gid)
                conn.setMembersOfGroup(group, new_members)

                return HttpResponseRedirect(reverse("wagroups"))
            context = {'form': form}
    elif action == 'edit':
        group = conn.getObject("ExperimenterGroup", gid)
        ownerIds = [e.id for e in group.getOwners()]

        memberIds = [m.id for m in group.getMembers()]

        permissions = getActualPermissions(group)
        form = GroupForm(
            initial={
                'name': group.name,
                'description': group.description,
                'permissions': permissions,
                'owners': ownerIds,
                'members': memberIds,
                'experimenters': experimenters
            })

        context = {'form': form, 'gid': gid, 'permissions': permissions}
    elif action == 'save':
        group = conn.getObject("ExperimenterGroup", gid)

        if request.method != 'POST':
            return HttpResponseRedirect(
                reverse(viewname="wamanagegroupid", args=["edit", group.id]))
        else:
            permissions = getActualPermissions(group)

            name_check = conn.checkGroupName(request.REQUEST.get('name'),
                                             group.name)
            form = GroupForm(initial={'experimenters': experimenters},
                             data=request.POST.copy(),
                             name_check=name_check)
            if form.is_valid():
                logger.debug("Update group form:" + str(form.cleaned_data))
                name = form.cleaned_data['name']
                description = form.cleaned_data['description']
                owners = form.cleaned_data['owners']
                permissions = form.cleaned_data['permissions']
                members = form.cleaned_data['members']

                listOfOwners = getSelectedExperimenters(conn, owners)
                if permissions != int(permissions):
                    perm = setActualPermissions(permissions)
                else:
                    perm = None
                conn.updateGroup(group, name, perm, listOfOwners, description)

                new_members = getSelectedExperimenters(
                    conn, mergeLists(members, owners))
                conn.setMembersOfGroup(group, new_members)

                return HttpResponseRedirect(reverse("wagroups"))
            context = {'form': form, 'gid': gid, 'permissions': permissions}
    else:
        return HttpResponseRedirect(reverse("wagroups"))

    context['template'] = template
    return context
Exemple #56
0
def manage_group(request, action, gid=None, conn=None, **kwargs):
    template = "webadmin/group_form.html"
    msgs = []

    user_privileges = conn.getCurrentAdminPrivileges()
    can_modify_group = 'ModifyGroup' in user_privileges
    can_add_member = 'ModifyGroupMembership' in user_privileges

    experimenters = list(conn.getObjects("Experimenter"))
    experimenters.sort(key=lambda x: x.getLastName().lower())

    system_groups = [
        conn.getAdminService().getSecurityRoles().systemGroupId,
        conn.getAdminService().getSecurityRoles().userGroupId,
        conn.getAdminService().getSecurityRoles().guestGroupId
    ]

    initial = {'experimenters': experimenters, 'permissions': 0}
    group_is_system = False
    name_check = False
    data = None
    if gid is not None:
        group = conn.getObject("ExperimenterGroup", gid)
        initial['name'] = group.name
        initial['description'] = group.description
        initial['owners'] = [e.id for e in group.getOwners()]
        initial['members'] = [m.id for m in group.getMembers()]
        initial['permissions'] = getActualPermissions(group)
        group_is_system = long(gid) in system_groups
    if request.method == 'POST':
        data = request.POST.copy()
        # name needs to be unique
        old_name = group.name if gid is not None else None
        name_check = conn.checkGroupName(request.POST.get('name'), old_name)
    form = GroupForm(initial=initial,
                     data=data,
                     name_check=name_check,
                     can_modify_group=can_modify_group,
                     can_add_member=can_add_member,
                     group_is_system=group_is_system)

    context = {'form': form}

    if action == 'new' or action == 'edit':
        # form prepared above - nothing else needed
        pass
    elif action == 'create':
        if request.method != 'POST':
            return HttpResponseRedirect(
                reverse(viewname="wamanagegroupid", args=["new"]))
        else:
            if form.is_valid():
                logger.debug("Create group form:" + str(form.cleaned_data))
                if can_modify_group:
                    name = form.cleaned_data['name']
                    description = form.cleaned_data['description']
                    permissions = form.cleaned_data['permissions']
                    perm = setActualPermissions(permissions)
                    gid = conn.createGroup(name, perm, description)
                if can_add_member:
                    owners = form.cleaned_data['owners']
                    members = form.cleaned_data['members']
                    group = conn.getObject("ExperimenterGroup", gid)
                    listOfOwners = getSelectedExperimenters(conn, owners)
                    conn.setOwnersOfGroup(group, listOfOwners)
                    new_members = getSelectedExperimenters(
                        conn, mergeLists(members, owners))
                    conn.setMembersOfGroup(group, new_members)

                return HttpResponseRedirect(reverse("wagroups"))
    elif action == 'save':
        if request.method != 'POST':
            return HttpResponseRedirect(
                reverse(viewname="wamanagegroupid", args=["edit", group.id]))
        else:
            if form.is_valid():
                logger.debug("Update group form:" + str(form.cleaned_data))
                if can_modify_group:
                    name = form.cleaned_data['name']
                    description = form.cleaned_data['description']
                    permissions = form.cleaned_data['permissions']

                    if permissions != int(permissions):
                        perm = setActualPermissions(permissions)
                    else:
                        perm = None

                    try:
                        msgs = conn.updateGroup(group, name, perm, description)
                    except omero.SecurityViolation, ex:
                        if ex.message.startswith('Cannot change permissions'):
                            msgs.append("Downgrade to private group not"
                                        " currently possible")
                        else:
                            msgs.append(ex.message)

                removalFails = []
                if can_add_member:
                    owners = form.cleaned_data['owners']
                    members = form.cleaned_data['members']

                    listOfOwners = getSelectedExperimenters(conn, owners)
                    conn.setOwnersOfGroup(group, listOfOwners)
                    new_members = getSelectedExperimenters(
                        conn, mergeLists(members, owners))
                    removalFails = conn.setMembersOfGroup(group, new_members)

                if len(removalFails) == 0 and len(msgs) == 0:
                    return HttpResponseRedirect(reverse("wagroups"))

                # If we've failed to remove user...
                # prepare error messages
                for e in removalFails:
                    url = reverse("wamanageexperimenterid",
                                  args=["edit", e.id])
                    msgs.append("Can't remove user <a href='%s'>%s</a> from"
                                " their only group" % (url, e.getFullName()))
                # Refresh form (ignore POST data)
                context['form'] = GroupForm(initial=initial,
                                            name_check=name_check,
                                            can_modify_group=can_modify_group,
                                            can_add_member=can_add_member,
                                            group_is_system=group_is_system)
Exemple #57
0
def index(request, error=None):
    # print('language: ' + str(request.LANGUAGE_CODE))
    languages = Language.objects.all()
    groups = Group.objects.filter(user=request.user)
    expression_form = ExpressionForm(user=request.user)
    return render(request, 'words/index.html', {'languages': languages, 'group_form': GroupForm(user=request.user),
                                                'groups': groups, 'expression_form': expression_form})
Exemple #58
0
def edit_group(request, group_id=None):
    if group_id:
        group = get_object_or_404(Group, pk=group_id)
    else:
        group = None

    if request.method == 'POST':
        if group:
            form = GroupForm(request.POST, instance=group)
        else:
            form = GroupForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        if group:
            form = GroupForm(instance=group)
        else:
            form = GroupForm()

    data = dict(form=form, group_id=group_id)
    return render_to_response('group/add_group.html',
                              data,
                              context_instance=RequestContext(request))
Exemple #59
0
def statistics(request):
    """
    тип графика
    название графика
    массив название
    массив данных
    подпись по x
    подпись по y
    """
    chart_type = 'column'
    chart_title = u'Название графика'
    row_title = u'Параметр'
    y_title = u'Ось Y'

    statistics = request.GET.get('statistics', 'requests')

    catalogs = ZCatalog.objects.all()
    start_date = datetime.datetime.now()
    end_date = datetime.datetime.now()
    date_group = u'2'  # группировка по дням
    attributes = []

    period_form = PeriodForm()
    group_form = GroupForm()
    attributes_form = AttributesForm()
    catalog_form = ZCatalogForm()
    if request.method == 'POST':
        period_form = PeriodForm(request.POST)
        group_form = GroupForm(request.POST)
        attributes_form = AttributesForm(request.POST)
        catalog_form = ZCatalogForm(request.POST)

        if period_form.is_valid():
            start_date = period_form.cleaned_data['start_date']
            end_date = period_form.cleaned_data['end_date']

        if group_form.is_valid():
            date_group = group_form.cleaned_data['group']

        if attributes_form.is_valid():
            attributes = attributes_form.cleaned_data['attributes']

        if catalog_form.is_valid():
            catalogs = catalog_form.cleaned_data['catalogs']

    if statistics == 'requests':
        attributes_form = None
        rows = requests_count(start_date=start_date,
                              end_date=end_date,
                              group=date_group,
                              catalogs=catalogs)
        chart_title = u'Число поисковых запросов по дате'
        row_title = u'Число поисковых запросов'
        y_title = u'Число поисковых запросов'

    elif statistics == 'attributes':
        group_form = None
        rows = requests_by_attributes(start_date=start_date,
                                      end_date=end_date,
                                      attributes=attributes,
                                      catalogs=catalogs)

        chart_title = u'Число поисковых запросов по поисковым атрибутам'
        row_title = u'Число поисковых запросов'
        y_title = u'Число поисковых запросов'
        chart_type = 'bar'

    elif statistics == 'terms':
        group_form = None
        rows = requests_by_term(start_date=start_date,
                                end_date=end_date,
                                attributes=attributes,
                                catalogs=catalogs)

        chart_title = u'Число поисковых запросов по фразам'
        row_title = u'Число поисковых запросов'
        y_title = u'Число поисковых запросов'
        chart_type = 'bar'
    else:
        return HttpResponse(u'Неправильный тип статистики')

    data_rows = json.dumps(rows, ensure_ascii=False)

    return render(
        request, 'zgate/administration/zcatalog_statistics.html', {
            'data_rows': data_rows,
            'catalog_form': catalog_form,
            'period_form': period_form,
            'group_form': group_form,
            'attributes_form': attributes_form,
            'chart_type': chart_type,
            'chart_title': chart_title,
            'y_title': y_title,
            'row_title': row_title,
            'active_module': 'zgate'
        })
Exemple #60
0
def manage_group(request, action, gid=None, conn=None, **kwargs):
    template = "webadmin/group_form.html"
    msgs = []
    
    experimenters = list(conn.getObjects("Experimenter"))
    experimenters.sort(key=lambda x: x.getLastName().lower())
    
    def getEditFormContext():
        group = conn.getObject("ExperimenterGroup", gid)
        ownerIds = [e.id for e in group.getOwners()]
        memberIds = [m.id for m in group.getMembers()]
        permissions = getActualPermissions(group)
        system_groups = [conn.getAdminService().getSecurityRoles().systemGroupId,
                         conn.getAdminService().getSecurityRoles().userGroupId,
                         conn.getAdminService().getSecurityRoles().guestGroupId]
        group_is_current_or_system = (conn.getEventContext().groupId == long(gid)) or (long(gid) in system_groups)
        form = GroupForm(initial={
            'name': group.name,
            'description':group.description,
            'permissions': permissions, 
            'owners': ownerIds,
            'members':memberIds,
            'experimenters':experimenters},
            group_is_current_or_system=group_is_current_or_system)
        admins = [conn.getAdminService().getSecurityRoles().rootId]
        if long(gid) in system_groups:
            # prevent removing 'root' or yourself from group if it's a system group
            admins.append(conn.getUserId())
        return {'form':form, 'gid': gid, 'permissions': permissions, "admins": admins}

    if action == 'new':
        form = GroupForm(initial={'experimenters':experimenters, 'permissions': 0})
        context = {'form':form}
    elif action == 'create':
        if request.method != 'POST':
            return HttpResponseRedirect(reverse(viewname="wamanagegroupid", args=["new"]))
        else:
            name_check = conn.checkGroupName(request.REQUEST.get('name'))
            form = GroupForm(initial={'experimenters':experimenters}, data=request.POST.copy(), name_check=name_check)
            if form.is_valid():
                logger.debug("Create group form:" + str(form.cleaned_data))
                name = form.cleaned_data['name']
                description = form.cleaned_data['description']
                owners = form.cleaned_data['owners']
                members = form.cleaned_data['members']
                permissions = form.cleaned_data['permissions']
                
                perm = setActualPermissions(permissions)
                listOfOwners = getSelectedExperimenters(conn, owners)
                gid = conn.createGroup(name, perm, listOfOwners, description)
                new_members = getSelectedExperimenters(conn, mergeLists(members,owners))
                group = conn.getObject("ExperimenterGroup", gid)
                conn.setMembersOfGroup(group, new_members)

                return HttpResponseRedirect(reverse("wagroups"))
            context = {'form':form}
    elif action == 'edit':
        context = getEditFormContext()
    elif action == 'save':
        group = conn.getObject("ExperimenterGroup", gid)
        
        if request.method != 'POST':
            return HttpResponseRedirect(reverse(viewname="wamanagegroupid", args=["edit", group.id]))
        else:
            permissions = getActualPermissions(group)
            
            name_check = conn.checkGroupName(request.REQUEST.get('name'), group.name)
            form = GroupForm(initial={'experimenters':experimenters}, data=request.POST.copy(), name_check=name_check)
            context = {'form':form, 'gid': gid, 'permissions': permissions}
            if form.is_valid():
                logger.debug("Update group form:" + str(form.cleaned_data))
                name = form.cleaned_data['name']
                description = form.cleaned_data['description']
                owners = form.cleaned_data['owners']
                permissions = form.cleaned_data['permissions']
                members = form.cleaned_data['members']
                
                listOfOwners = getSelectedExperimenters(conn, owners)
                if permissions != int(permissions):
                    perm = setActualPermissions(permissions)
                else:
                    perm = None

                context = getEditFormContext()
                context['ome'] = {}
                
                permissions_error = False
                try:
                    conn.updateGroup(group, name, perm, listOfOwners, description)
                except omero.SecurityViolation, ex:
                    if ex.message.startswith('Cannot change permissions'):
                        permissions_error = True
                        msgs.append("Downgrade to private group not currently possible")
                    else:
                        msgs.append(ex.message)
                
                new_members = getSelectedExperimenters(conn, mergeLists(members,owners))
                removalFails = conn.setMembersOfGroup(group, new_members)
                if len(removalFails) == 0 and not permissions_error:
                    return HttpResponseRedirect(reverse("wagroups"))
                # If we've failed to remove user...
                
                # prepare error messages
                for e in removalFails:
                    url = reverse("wamanageexperimenterid", args=["edit", e.id])
                    msgs.append("Can't remove user <a href='%s'>%s</a> from their only group"
                        % (url, e.getFullName()))
                # refresh the form and add messages
                context = getEditFormContext()