def form_query(self, query): if self.search: query = query.filter( Q(last_name__icontains=self.search) | Q(first_name__icontains=self.search) | Q(surname__icontains=self.search) | Q(username__icontains=self.search)) if self.year and self.year != 'all': query = query.filter(year=self.year) if self.state and self.state != 'all': if self.state == 'internals': query = query.exclude(groups=get_members_group( is_externals=True)).filter(is_active=True) if self.state == 'negative_balance': query = query.filter(balance__lt=0.0, is_active=True) elif self.state == 'threshold': threshold = configuration_get( 'BALANCE_THRESHOLD_PURCHASE').get_value() query = query.filter(balance__lt=threshold, is_active=True) elif self.state == 'unactive': query = query.filter(is_active=False) else: query = query.filter(is_active=True) return query
def get_form_kwargs(self): """ Add possible members and permissions to kwargs of the form. Possible members are all members, except externals members and unactive users. Possible permissions are all permissions. :note:: For the special case of a shop management, two groups exist: group of chiefs and group of associates. If the group of associates is managed, possible permissions are only permissions of the chiefs group. """ kwargs = super().get_form_kwargs() if self.group.name.startswith('associates-') is True: chiefs_group_name = self.group.name.replace('associates', 'chiefs') query = Group.objects.get( name=chiefs_group_name).permissions.all().exclude( name=self.perm_manage_group[0]) else: query = Permission.objects.all() kwargs['possible_permissions'] = query.exclude( pk__in=human_unused_permissions()) kwargs['possible_members'] = User.objects.filter( is_active=True).exclude(groups=get_members_group( is_externals=True)) return kwargs
def post(self, request, *args, **kwargs): wb = Workbook() # grab the active worksheet ws = wb.active ws.title = "event" columns = ['Username', 'Pondération', 'Infos (Non utilisées) ->', 'Nom Prénom', 'Bucque'] ws.append(columns) for col in ['A','B','C','D','E']: ws.column_dimensions[col].width = 30 state = request.POST.get("state", "") years = request.POST.getlist("years", "") if state == 'year': if years: # Contains the years selected list_year_result = years users = User.objects.filter(year__in=list_year_result, is_active=True).exclude( groups=get_members_group(is_externals=True)).order_by('-year','username') for u in users: ws.append([u.username, '', '', u.last_name + ' ' + u.first_name, u.surname]) else: raise Http404 elif state == 'participants': list_participants_weight = self.event.list_participants_weight() for e in list_participants_weight: u = e[0] ws.append([u.username, e[1], '', u.last_name + ' ' + u.first_name, u.surname]) elif state == 'registrants': list_registrants_weight = self.event.list_registrants_weight() for e in list_registrants_weight: u = e[0] ws.append([u.username, e[1], '', u.last_name + ' ' + u.first_name, u.surname]) else: raise Http404 # Return the file response = HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=event-'+str(self.event.datetime.date())+".xlsx" return response
def post(self, request, *args, **kwargs): deactivated = False if self.user.is_active is True: events = self.user.manager.filter(done=False) if events.count() > 0: for event in events: self.error_event_message += "\n - " + event.description messages.warning(request, self.error_event_message) else: deactivated = True self.user.is_active = False # si c'est un gadz. Special members can't be added to other groups if get_members_group() in self.user.groups.all(): self.user.groups.set([ get_members_group(), ]) self.user.save() else: self.user.is_active = True self.user.save() if self.user.is_active: self.success_message += 'activé' else: self.success_message += 'désactivé' messages.success(request, self.success_message % dict(user=self.user, )) if request.user == self.user and deactivated: success_url = reverse('url_logout') else: success_url = reverse('url_user_retrieve', kwargs={'user_pk': self.user.pk}) return redirect(force_text(success_url))
def test_create_external_member(self): response_creation = self.client1.post( reverse(self.url_view), { 'first_name': 'first_name2', 'last_name': 'last_name2', 'email': '*****@*****.**', 'year': 2015, 'username': '******', 'is_external_member': True, 'password': '******' }) self.assertEqual(response_creation.status_code, 302) self.assertTrue(Client().login(username='******', password='******')) user = User.objects.get(username='******') self.assertEqual(user.groups.count(), 1) self.assertEqual(user.groups.first(), get_members_group(is_externals=True))
def test_create_internal_member(self): response_creation = self.client1.post( reverse(self.url_view), { 'first_name': 'first_name', 'last_name': 'last_name', 'email': '*****@*****.**', 'family': '53', 'year': 2015, 'campus': 'ME', 'username': '******', 'password': '******' }) self.assertEqual(response_creation.status_code, 302) self.assertTrue(Client().login(username='******', password='******')) user = User.objects.get(username='******') self.assertEqual(user.groups.count(), 1) self.assertEqual(user.groups.first(), get_members_group())
def form_valid(self, form): user = User.objects.create(username=form.cleaned_data['username'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email=form.cleaned_data['email'], surname=form.cleaned_data['surname'], family=form.cleaned_data['family'], campus=form.cleaned_data['campus'], year=form.cleaned_data['year']) user.set_password(form.cleaned_data['password']) user.save() is_external_member = form.cleaned_data['is_external_member'] user.groups.add(get_members_group(is_external_member)) user.save() # User object is assigned to self.object (so we can access to it in get_success_url) self.object = user return super().form_valid(form)
def form_valid(self, form): try: wb = openpyxl.load_workbook(self.request.FILES['list_user'], read_only=True) sheet = wb.active rows = sheet.rows except: raise PermissionDenied errors = [] nb_empty_rows = 0 min_col = sheet.min_column max_col = sheet.max_column min_row = sheet.min_row i = min_row columns = form.cleaned_data['xlsx_columns'] # Setting column numbers for col in range(min_col, max_col + 1): if sheet.cell(None, sheet.min_row, col).value == 'username': col_username = col - min_row elif sheet.cell(None, sheet.min_row, col).value == 'first_name': col_first_name = col - min_row elif sheet.cell(None, sheet.min_row, col).value == 'last_name': col_last_name = col - min_row elif sheet.cell(None, sheet.min_row, col).value == 'email': col_email = col - min_row elif sheet.cell(None, sheet.min_row, col).value == 'surname': col_surname = col - min_row elif sheet.cell(None, sheet.min_row, col).value == 'family': col_family = col - min_row elif sheet.cell(None, sheet.min_row, col).value == 'campus': col_campus = col - min_row elif sheet.cell(None, sheet.min_row, col).value == 'year': col_year = col - min_row for _ in range(min_row): next(rows) skipped_rows = [] # Saving users for row in rows: i += 1 try: user_dict = {} errors_on_required_columns = [] skipped_row = False try: if row[col_username].value: user_dict['username'] = row[col_username].value.strip() else: skipped_row = True nb_empty_rows += 1 except: skipped_row = True errors_on_required_columns.append('username') if 'first_name' in columns: try: if row[col_first_name].value: user_dict['first_name'] = row[ col_first_name].value.strip() except: errors_on_required_columns.append('first_name') if 'last_name' in columns: try: if row[col_last_name].value: user_dict['last_name'] = row[ col_last_name].value.strip() except: errors_on_required_columns.append('last_name') if 'email' in columns: try: if row[col_email].value: user_dict['email'] = row[col_email].value.strip() except: errors_on_required_columns.append('email') if 'surname' in columns: try: if row[col_surname].value: user_dict['surname'] = row[ col_surname].value.strip() except: errors_on_required_columns.append('surname') if 'family' in columns: try: if row[col_family].value: user_dict['family'] = str( row[col_family].value).strip() except: errors_on_required_columns.append('family') if 'campus' in columns: try: if row[col_campus].value: user_dict['campus'] = row[col_campus].value.strip() except: errors_on_required_columns.append('campus') if 'year' in columns: try: if row[col_year].value: user_dict['year'] = int(row[col_year].value) except: errors_on_required_columns.append('year') if not skipped_row: username = user_dict['username'] if User.objects.filter(username=username).count() > 0: User.objects.filter(username=username).update( **user_dict) else: user = User.objects.create(**user_dict) user.set_password(''.join(random.SystemRandom().choice( string.ascii_uppercase + string.digits) for _ in range(20))) user = User.objects.get(username=username) user.save() user.groups.add(get_members_group()) else: skipped_rows.append(str(i)) except: if str(i) in skipped_rows: errors.append( "La ligne n*" + str(i) + "n'a pas été traitée car le username est manquant" ) # TODO: Make this error appear elif errors_on_required_columns: errors.append( "Les colonnes " + ", ".join(errors_on_required_columns) + " sont requis et comportent des erreurs (ligne n*" + str(i) + ")") else: errors.append( "Une erreur empêche le traitement du fichier Excel (ligne n*" + str(i) + ")") error_message = "" error_message += "\n - ".join(errors) messages.success( self.request, str(i - len(skipped_rows) - min_row - len(errors)) + " utilisateurs ont été crées/mis à jour") messages.warning(self.request, error_message) return super().form_valid(form)