def archive_order(request): # expects a comma-separated list of archive slugs ids = request.POST.get('ids', None) if not ids: return HttpResponseBadRequest() slugs = ids.split(',') # find all archives matching any of the slugs passed in archives = Archive.objects.filter(slug__in=slugs) # re-sort according to the order in the request archives = sorted(archives, key=lambda arch: slugs.index(arch.slug)) # save order to user account try: arc = request.user.archivist except ObjectDoesNotExist: # if for some reason user model does not have an archivist, # create one so we can store the order preference arc = Archivist() request.user.archivist = arc arc.order = ','.join([str(a.id) for a in archives]) request.user.archivist.save() return HttpResponse('Updated order')
def test_sorted_archives(self): # create some test archives to associate with test user marbl = Archive(label='MARBL', name='Manuscipts', svn='https://svn.co/ead', slug='marbl') marbl.save() eua = Archive(label='EUA', name='Archives', svn='https://svn.co/ead', slug='eua') eua.save() theo = Archive(label='Theology', name='Papers', svn='https://svn.co/ead', slug='theo') theo.save() # NOTE: consider making this a fixture? # no archives or order = empty list, no errors arc = Archivist(user=User.objects.get(username='******')) arc.save() # because admin is super, should see all archives self.assertEqual(3, arc.sorted_archives().count()) arc.archives.add(marbl, eua, theo) arc.user.is_superuser = False # no order default = Archive.objects.all() self.assertEqual([a.id for a in default], [a.id for a in arc.sorted_archives()]) # partial order arc.order = ','.join([str(eua.id), str(theo.id)]) ordered_archives = arc.sorted_archives() self.assertEqual(eua.id, ordered_archives[0].id) self.assertEqual(theo.id, ordered_archives[1].id) # since not specified, should be put last self.assertEqual(marbl.id, ordered_archives[2].id) # no explicit archives and not super = empty list arc.archives.clear() self.assertEqual([], arc.sorted_archives())