Exemplo n.º 1
0
 def post(self, request, *args, **kwargs):
     """
     Handles POST requests, instantiating a form instance with the passed
     POST variables and then checked for validity.
     """
     with transaction.atomic():
         # save language preference:
         language = request.POST.get('language', None)
         if language is not None and language in (lang for lang, label in settings.LANGUAGES):
             request.user.cosinnus_profile.language = language
             request.user.cosinnus_profile.save(update_fields=['language'])
         
         # save moderator status, only if portal admin
         is_moderator = bool(request.POST.get('is_moderator', False))
         if check_user_portal_admin(request.user):
             membership = CosinnusPortalMembership.objects.get(group=CosinnusPortal.get_current(), user=request.user)
             if membership.is_moderator != is_moderator:
                 membership.is_moderator = is_moderator
                 membership.save()
         
         # save global notification setting
         global_setting = int(request.POST.get('global_setting', '-1'))
         if global_setting >= 0 and global_setting in (sett for sett, label in GlobalUserNotificationSetting.SETTING_CHOICES):
             setting_obj = GlobalUserNotificationSetting.objects.get_object_for_user(request.user)
             setting_obj.setting = global_setting
             setting_obj.save()
             
         # save all multi preference choices
         for multi_notification_id, __ in MULTI_NOTIFICATION_IDS.items():
             multi_choice = int(request.POST.get('multi_pref__%s' % multi_notification_id, '-1'))
             if multi_choice >= 0 and multi_choice in (sett for sett, label in UserMultiNotificationPreference.SETTING_CHOICES):
                 multi_pref, created = UserMultiNotificationPreference.objects.get_or_create(user=self.request.user, multi_notification_id=multi_notification_id, portal=CosinnusPortal.get_current())
                 if created or multi_pref.setting != multi_choice:
                     multi_pref.setting = multi_choice
                     multi_pref.save()
         
         # only update the individual group settings if user selected the individual global setting
         if global_setting == GlobalUserNotificationSetting.SETTING_GROUP_INDIVIDUAL:            
             for name, value in list(request.POST.items()):
                 # we go through all values POSTed to us. some of these are the settings from the dropdown
                 # box (all / none / custom), some of them are the individual custom preference choices
                 # for a group.
                 # depending of the dropdown setting we set the global all/none setting and ignore the custom
                 # values, or if set to custom, delete any global all/none preference entries for that group
                 # and save the individual preference settings for that group
                 if not name.startswith('notif_'):
                     continue
                 if name.startswith('notif_choice:'):
                     group_id = int(name.split(':')[1])
                     group = CosinnusGroup.objects.get_cached(pks=group_id)
                     set_user_group_notifications_special(request.user, group, value)
                 elif name.startswith('notif_option:'):
                     # if we are looking at a group item, check if the choice field is set to custom,
                     # otherwise ignore it
                     value = int(value)
                     _, group_id, notification_id = name.split(':')
                     if request.POST.get('notif_choice:%s' % group_id, None) == 'custom':
                         # save custom settings if the main switch for custom is enabled:
                         group = CosinnusGroup.objects.get_cached(pks=int(group_id))
                         # save / erase setting
                         try:
                             pref = UserNotificationPreference.objects.get(user=request.user, group=group, notification_id=notification_id)
                             if value in list(dict(UserNotificationPreference.SETTING_CHOICES).keys()) and value != pref.setting:
                                 pref.setting = value
                                 pref.save()
                         except UserNotificationPreference.DoesNotExist:
                             pref = UserNotificationPreference.objects.create(user=request.user, group=group, notification_id=notification_id, setting=value)
     
     messages.success(request, self.message_success)
     return HttpResponseRedirect(self.success_url)
Exemplo n.º 2
0
def is_portal_admin_of(user, portal):
    """
    Template filter to check if a user is a portal admin.
    """
    return check_user_portal_admin(user, portal=portal)
Exemplo n.º 3
0
 def import_project_view(request):
     if not (request.user.is_superuser or check_user_portal_admin(request.user)):
         return HttpResponseForbidden()
     
     debug = '-'
     import_running = cache.get(GROUP_IMPORT_RUNNING_CACHE_KEY)
     import_results = cache.get(GROUP_IMPORT_RESULTS_CACHE_KEY)
         
     
     if not import_running and request.method == 'POST':
         if request.POST.get('trigger_new_import', False):
             cache.delete(GROUP_IMPORT_RESULTS_CACHE_KEY)
             return redirect(reverse('import-projects'))
         elif import_results:
             messages.success(request, dotrans_('An import has just finished. Please click the "Start a new import" button to start a new one!'))
         else:
             csv_file_groups = request.FILES.get('csv_upload_groups', None)
             csv_file_users = request.FILES.get('csv_upload_users', None)
             
             if csv_file_groups and csv_file_users:
                 messages.error(request, dotrans_('You uploaded a CSV file for both projects/groups AND users! Please only upload one file to import at a time!'))
             elif not (csv_file_groups or csv_file_users):
                 messages.error(request, dotrans_('You did not upload a CSV file or something went wrong during the upload!'))
             else:
                 csv_file = csv_file_groups or csv_file_users
                 import_type = 'groups' if csv_file_groups else 'users'
                 
                 encoding = request.POST.get('encoding', "utf-8")
                 delimiter = request.POST.get('delimiter', ',')
                 delimiter = str(delimiter)[0]
                 
                 try:
                     debug = csv_import_projects(csv_file, request=request, encoding=encoding, delimiter=delimiter, import_type=import_type)
                     messages.success(request, dotrans_('The CSV file was read successfully! You will be notified by email when it completes.'))
                     import_running = True
                 except (UnicodeDecodeError, UnicodeError):
                     messages.error(request, dotrans_('The CSV file you supplied is not formatted in the proper encoding (%s)!' % encoding))
                 except EmptyOrUnreadableCSVContent:
                     messages.error(request, dotrans_('The CSV file you supplied was empty or not formatted in the proper encoding (%(encoding)s) or with a wrong delimiter (%(delimiter)s)!' % {'encoding':encoding, 'delimiter':delimiter}))
                 except UnexpectedNumberOfColumns as e:
                     messages.error(request, dotrans_('One or more rows in the CSV file you supplied contained less columns than expected (%s)! Either the file was read in a wrong encoding, or the file was using a different format than the server expected.' % str(e)))
                 except ImportAlreadyRunning:
                     messages.error(request, dotrans_('Another import is currently running! Please wait till that one is finished.'))
                 except ImproperlyConfigured as e:
                     messages.error(request, dotrans_('A CSV configuration error occured, has the CSV format changed?. Message was: %s') % str(e))
                 except Exception as e:
                     messages.error(request, dotrans_('There was an unexpected error when reading the CSV file! Please make sure the file is properly formatted. If the problem persists, please contact an administrator!'))
                     logger.warn('A CSV file uploaded for import encountered an unexpected error! The exception was: "%s"' % str(e), extra={'encoding_used': encoding, 'delimiter_used': delimiter})
                     if getattr(settings, 'DEBUG_LOCAL', False):
                         raise
     
     context = {
         'site_name': settings.WAGTAIL_SITE_NAME,
         'panels': [],
         'user': request.user,
     }
     if import_running and request.GET.get('force_stop', None):
         # enables clearing the cache if the thread has stopped, like after a server reboot during import
         import_running = False
         cache.delete(GROUP_IMPORT_RUNNING_CACHE_KEY)
         template = "cosinnus/wagtail/wagtailadmin/import_projects.html"
     if import_running:
         import_progress = cache.get(GROUP_IMPORT_PROGRESS_CACHE_KEY, 0)
         context.update({'import_progress': import_progress})
         template = "cosinnus/wagtail/wagtailadmin/import_projects_running.html"
     elif import_results:
         context.update({'import_results': import_results})
         template = "cosinnus/wagtail/wagtailadmin/import_projects_results.html"
     else:
         template = "cosinnus/wagtail/wagtailadmin/import_projects.html"
         
     return render(request, template, context)