def test_post_with_collections(self): root_collection = Collection.get_first_root_node() evil_plans_collection = root_collection.add_child(name="Evil plans") # Build a fake file fake_file = ContentFile(b("A boring example document")) fake_file.name = 'test.txt' # Submit post_data = { 'title': "Test document", 'file': fake_file, 'collection': evil_plans_collection.id, } response = self.client.post(reverse('wagtaildocs:add'), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtaildocs:index')) # Document should be created, and be placed in the Evil Plans collection self.assertTrue(models.Document.objects.filter(title="Test document").exists()) root_collection = Collection.get_first_root_node() self.assertEqual( models.Document.objects.get(title="Test document").collection, evil_plans_collection )
def test_add_post_with_collections(self): """ This tests that a POST request to the add view saves the document and returns an edit form, when collections are active """ root_collection = Collection.get_first_root_node() evil_plans_collection = root_collection.add_child(name="Evil plans") response = self.client.post(reverse('wagtaildocs:add_multiple'), { 'files[]': SimpleUploadedFile('test.png', b"Simple text document"), 'collection': evil_plans_collection.id }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') # Check response self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertTemplateUsed(response, 'wagtaildocs/multiple/edit_form.html') # Check document self.assertIn('doc', response.context) self.assertEqual(response.context['doc'].title, 'test.png') self.assertTrue(response.context['doc'].file_size) self.assertTrue(response.context['doc'].file_hash) # check that it is in the 'evil plans' collection doc = models.get_document_model().objects.get(title='test.png') root_collection = Collection.get_first_root_node() self.assertEqual(doc.collection, evil_plans_collection) # Check form self.assertIn('form', response.context) self.assertEqual( set(response.context['form'].fields), set(models.get_document_model().admin_form_fields) - {'file'} | {'collection'}, ) self.assertEqual(response.context['form'].initial['title'], 'test.png') # Check JSON response_json = json.loads(response.content.decode()) self.assertIn('doc_id', response_json) self.assertIn('form', response_json) self.assertIn('success', response_json) self.assertEqual(response_json['doc_id'], response.context['doc'].id) self.assertTrue(response_json['success']) # form should contain a collection chooser self.assertIn('Collection', response_json['form'])
def setUp(self): # Build a fake file fake_file = ContentFile(b("A boring example document")) fake_file.name = 'test.txt' self.root_collection = Collection.get_first_root_node() self.evil_plans_collection = self.root_collection.add_child(name="Evil plans") self.nice_plans_collection = self.root_collection.add_child(name="Nice plans") # Create a document to edit self.document = models.Document.objects.create( title="Test document", file=fake_file, collection=self.nice_plans_collection ) # Create a user with change_document permission but not add_document user = get_user_model().objects.create_user( username='******', email='*****@*****.**', password='******' ) change_permission = Permission.objects.get( content_type__app_label='wagtaildocs', codename='change_document' ) admin_permission = Permission.objects.get( content_type__app_label='wagtailadmin', codename='access_admin' ) self.changers_group = Group.objects.create(name='Document changers') GroupCollectionPermission.objects.create( group=self.changers_group, collection=self.root_collection, permission=change_permission ) user.groups.add(self.changers_group) user.user_permissions.add(admin_permission) self.assertTrue(self.client.login(username='******', password='******'))
def setUp(self): # Create some user accounts for testing permissions User = get_user_model() self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.owner = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.editor = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.editor.groups.add(Group.objects.get(name='Editors')) self.administrator = User.objects.create_superuser( username='******', email='*****@*****.**', password='******' ) # Owner user must have the add_image permission image_adders_group = Group.objects.create(name="Image adders") GroupCollectionPermission.objects.create( group=image_adders_group, collection=Collection.get_first_root_node(), permission=Permission.objects.get(codename='add_image'), ) self.owner.groups.add(image_adders_group) # Create an image for running tests on self.image = Image.objects.create( title="Test image", uploaded_by_user=self.owner, file=get_test_image_file(), )
def test_post_video_with_collections(self): root_collection = Collection.get_first_root_node() evil_plans_collection = root_collection.add_child(name="Evil plans") # Build a fake file fake_file = ContentFile(b("A boring example movie")) fake_file.name = 'movie.mp3' # Submit post_data = { 'title': "Test media", 'file': fake_file, 'duration': 100, 'collection': evil_plans_collection.id, } response = self.client.post(reverse('wagtailmedia:add', args=('video', )), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtailmedia:index')) # Media should be created, and be placed in the Evil Plans collection self.assertTrue(models.Media.objects.filter(title="Test media").exists()) media = models.Media.objects.get(title="Test media") self.assertEqual(media.collection, evil_plans_collection) self.assertEqual(media.type, 'video')
def setUp(self): # Build a fake file fake_file = ContentFile(b("A boring example song")) fake_file.name = 'song.mp3' self.root_collection = Collection.get_first_root_node() self.evil_plans_collection = self.root_collection.add_child(name="Evil plans") self.nice_plans_collection = self.root_collection.add_child(name="Nice plans") # Create a media to edit self.media = models.Media.objects.create( title="Test media", file=fake_file, collection=self.nice_plans_collection, duration=100 ) # Create a user with change_media permission but not add_media user = get_user_model().objects.create_user( username='******', email='*****@*****.**', password='******' ) change_permission = Permission.objects.get( content_type__app_label='wagtailmedia', codename='change_media' ) admin_permission = Permission.objects.get( content_type__app_label='wagtailadmin', codename='access_admin' ) self.changers_group = Group.objects.create(name='Media changers') GroupCollectionPermission.objects.create( group=self.changers_group, collection=self.root_collection, permission=change_permission ) user.groups.add(self.changers_group) user.user_permissions.add(admin_permission) self.assertTrue(self.client.login(username='******', password='******'))
def test_pagination_preserves_other_params(self): root_collection = Collection.get_first_root_node() evil_plans_collection = root_collection.add_child(name="Evil plans") for i in range(1, 50): self.image = Image.objects.create( title="Test image %i" % i, file=get_test_image_file(), collection=evil_plans_collection ) response = self.get({'collection_id': evil_plans_collection.id, 'p': 2}) self.assertEqual(response.status_code, 200) response_body = response.content.decode('utf8') # prev link should exist and include collection_id self.assertTrue( ("?p=1&collection_id=%i" % evil_plans_collection.id) in response_body or ("?collection_id=%i&p=1" % evil_plans_collection.id) in response_body ) # next link should exist and include collection_id self.assertTrue( ("?p=3&collection_id=%i" % evil_plans_collection.id) in response_body or ("?collection_id=%i&p=3" % evil_plans_collection.id) in response_body )
def setUp(self): add_doc_permission = Permission.objects.get( content_type__app_label='wagtaildocs', codename='add_document' ) admin_permission = Permission.objects.get( content_type__app_label='wagtailadmin', codename='access_admin' ) root_collection = Collection.get_first_root_node() self.evil_plans_collection = root_collection.add_child(name="Evil plans") conspirators_group = Group.objects.create(name="Evil conspirators") conspirators_group.permissions.add(admin_permission) GroupCollectionPermission.objects.create( group=conspirators_group, collection=self.evil_plans_collection, permission=add_doc_permission ) user = get_user_model().objects.create_user( username='******', email='*****@*****.**', password='******' ) user.groups.add(conspirators_group) self.client.login(username='******', password='******')
def test_post(self): # Build a fake file fake_file = ContentFile(b("A boring example document")) fake_file.name = 'test.txt' # Submit post_data = { 'title': "Test document", 'file': fake_file, } response = self.client.post(reverse('wagtaildocs:add'), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtaildocs:index')) # Document should be created, and be placed in the root collection document = models.Document.objects.get(title="Test document") root_collection = Collection.get_first_root_node() self.assertEqual( document.collection, root_collection ) # Check that the file_size field was set self.assertTrue(document.file_size)
def index(request): Image = get_image_model() # Get images (filtered by user permission) images = permission_policy.instances_user_has_any_permission_for( request.user, ['change', 'delete'] ).order_by('-created_at') # Search query_string = None if 'q' in request.GET: form = SearchForm(request.GET, placeholder=_("Search images")) if form.is_valid(): query_string = form.cleaned_data['q'] images = images.search(query_string) else: form = SearchForm(placeholder=_("Search images")) # Filter by collection current_collection = None collection_id = request.GET.get('collection_id') if collection_id: try: current_collection = Collection.objects.get(id=collection_id) images = images.filter(collection=current_collection) except (ValueError, Collection.DoesNotExist): pass paginator = Paginator(images, per_page=20) images = paginator.get_page(request.GET.get('p')) collections = permission_policy.collections_user_has_any_permission_for( request.user, ['add', 'change'] ) if len(collections) < 2: collections = None else: collections = Collection.order_for_display(collections) # Create response if request.is_ajax(): return render(request, 'wagtailimages/images/results.html', { 'images': images, 'query_string': query_string, 'is_searching': bool(query_string), }) else: return render(request, 'wagtailimages/images/index.html', { 'images': images, 'query_string': query_string, 'is_searching': bool(query_string), 'search_form': form, 'popular_tags': popular_tags_for_model(Image), 'collections': collections, 'current_collection': current_collection, 'user_can_add': permission_policy.user_has_permission(request.user, 'add'), })
def setUp(self): self.root_collection = Collection.get_first_root_node() self.holiday_photos_collection = self.root_collection.add_child( name="Holiday photos" ) self.evil_plans_collection = self.root_collection.add_child( name="Evil plans" )
def test_index_with_collection(self): root_collection = Collection.get_first_root_node() root_collection.add_child(name="Evil plans") self.make_docs() response = self.client.get(reverse('wagtaildocs:index')) self.assertContains(response, '<th>Collection</th>') self.assertContains(response, '<td>Root</td>')
def test_ordering(self): root_collection = Collection.get_first_root_node() root_collection.add_child(name="Milk") root_collection.add_child(name="Bread") root_collection.add_child(name="Avacado") response = self.get() self.assertEqual( [collection.name for collection in response.context['object_list']], ['Avacado', 'Bread', 'Milk'])
def dummy_wagtail_doc(request): if not Collection.objects.exists(): # pragma: no cover Collection.add_root() doc = Document(title='hello') doc.file.save('foo.txt', ContentFile('foo', 'foo.txt')) doc.save() doc = Document.objects.get(pk=doc.pk) # Reload to ensure the upload took def nuke(): try: # Try cleaning up so `/var/media` isn't full of foo doc.file.delete() doc.delete() except: # pragma: no cover pass request.addfinalizer(nuke) return doc
def test_get_with_collections(self): root_collection = Collection.get_first_root_node() root_collection.add_child(name="Evil plans") response = self.client.get(reverse('wagtaildocs:add')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtaildocs/documents/add.html') self.assertContains(response, '<label for="id_collection">') self.assertContains(response, "Evil plans")
def test_get_with_collections(self): root_collection = Collection.get_first_root_node() root_collection.add_child(name="Evil plans") response = self.get() self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailimages/images/add.html') self.assertContains(response, '<label for="id_collection">') self.assertContains(response, "Evil plans")
def test_index_with_collection(self): root_collection = Collection.get_first_root_node() root_collection.add_child(name="Evil plans") root_collection.add_child(name="Good plans") self.make_docs() response = self.client.get(reverse('wagtaildocs:index')) self.assertContains(response, '<th>Collection</th>') self.assertContains(response, '<td>Root</td>') self.assertEqual( [collection.name for collection in response.context['collections']], ['Root', 'Evil plans', 'Good plans'])
def test_ordering(self): root_collection = Collection.get_first_root_node() root_collection.add_child(name="Milk") root_collection.add_child(name="Bread") root_collection.add_child(name="Avocado") response = self.get() # Note that the Collections have been automatically sorted by name. self.assertEqual( [ collection.name for collection in response.context["object_list"] ], ["Avocado", "Bread", "Milk"], )
def test_add_with_collections(self): root_collection = Collection.get_first_root_node() root_collection.add_child(name="Evil plans") # Send request response = self.client.get(reverse('wagtaildocs:add_multiple')) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtaildocs/multiple/add.html') # collection chooser should exisst self.assertContains(response, '<label for="id_adddocument_collection">') self.assertContains(response, 'Evil plans')
def login_as_baker(self): # Create group with access to admin and Chooser permission on one Collection, but not another. bakers_group = Group.objects.create(name='Bakers') access_admin_perm = Permission.objects.get( content_type__app_label='wagtailadmin', codename='access_admin') bakers_group.permissions.add(access_admin_perm) # Create the "Bakery" Collection and grant "choose" permission to the Bakers group. root = Collection.objects.get(id=get_root_collection_id()) bakery_collection = root.add_child(instance=Collection(name='Bakery')) GroupCollectionPermission.objects.create( group=bakers_group, collection=bakery_collection, permission=Permission.objects.get( content_type__app_label='wagtaildocs', codename='choose_document')) # Create the "Office" Collection and _don't_ grant any permissions to the Bakers group. root.add_child(instance=Collection(name='Office')) # Create a Baker user. user = self.create_user(username="******", password="******") user.groups.add(bakers_group) # Log in as the baker. self.login(user)
def test_post(self): response = self.post({ 'name': "Holiday snaps", }) # Should redirect back to index self.assertRedirects(response, reverse('wagtailadmin_collections:index')) # Check that the collection was created and is a child of root self.assertEqual(Collection.objects.filter(name="Holiday snaps").count(), 1) root_collection = Collection.get_first_root_node() self.assertEqual( Collection.objects.get(name="Holiday snaps").get_parent(), root_collection )
def get_chooser_context(request): """Helper function to return common template context variables for the main chooser view""" collections = Collection.objects.all() if len(collections) < 2: collections = None else: collections = Collection.order_for_display(collections) return { 'searchform': SearchForm(), 'is_searching': False, 'query_string': None, 'popular_tags': popular_tags_for_model(get_media_model()), 'collections': collections, }
def __init__(self, *args, **kwargs): kwargs.pop("user") super(forms.ModelForm, self).__init__(*args, **kwargs) # Get or initiate the Public uploads collection. try: public_collection = Collection.objects.get( name=NON_ADMIN_DRAFTAIL_PUBLIC_COLLECTION_NAME ) except Collection.DoesNotExist: root_coll = Collection.get_first_root_node() root_coll.add_child(name=NON_ADMIN_DRAFTAIL_PUBLIC_COLLECTION_NAME) public_collection = Collection.objects.get( name=NON_ADMIN_DRAFTAIL_PUBLIC_COLLECTION_NAME ) self.collections = [public_collection]
def ensure(self, name: str) -> Collection: """Ensures that a collection called ``name`` exists, and returns that collection. Args: name (str): The name of the collection you want """ try: coll = Collection.objects.get(name=name) except Collection.DoesNotExist: try: root_collection = Collection.get_first_root_node() coll = root_collection.add_child(name=name) except Exception: raise return coll
def handle(self, *args, **options): all_products = ProductPage.objects.all() total_products = all_products.count() try: pni_collection = Collection.objects.get(name="PNI Images") except Collection.DoesNotExist: root_collection = Collection.get_first_root_node() pni_collection = root_collection.add_child(name="PNI Images") for index, product in enumerate(all_products): print(f"Processing product {index+1} of {total_products}") if product.cloudinary_image: mime = MimeTypes() mime_type = mime.guess_type( product.cloudinary_image.url) # -> ('image/jpeg', None) if mime_type: mime_type = mime_type[0].split('/')[1].upper() else: # Default to a JPEG mimetype. mime_type = 'JPEG' # Temporarily download the image response = requests.get(product.cloudinary_image.url, stream=True) if response.status_code == 200: # Create an image out of the Cloudinary URL and write it to a PIL Image. pil_image = PILImage.open(response.raw) f = BytesIO() pil_image.save(f, mime_type) # Get the file name in a nice way. new_image_name = ntpath.basename( product.cloudinary_image.url) # Store the image as a WagtailImage object wagtail_image = WagtailImage.objects.create( title=new_image_name, file=ImageFile(f, name=new_image_name), collection=pni_collection) # Associate product.image with wagtail_image product.image = wagtail_image # Always generate a new revision. revision = product.save_revision() if product.live: # Re-publish existing "live" pages from the latest revision revision.publish()
def test_add_post(self): """ This tests that a POST request to the add view saves the document and returns an edit form """ response = self.client.post(reverse('wagtaildocs:add_multiple'), { 'files[]': SimpleUploadedFile('test.png', b"Simple text document"), }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') # Check response self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertTemplateUsed(response, 'wagtaildocs/multiple/edit_form.html') # Check document self.assertIn('doc', response.context) self.assertEqual(response.context['doc'].title, 'test.png') self.assertTrue(response.context['doc'].file_size) self.assertTrue(response.context['doc'].file_hash) # check that it is in the root collection doc = get_document_model().objects.get(title='test.png') root_collection = Collection.get_first_root_node() self.assertEqual(doc.collection, root_collection) # Check form self.assertIn('form', response.context) self.assertEqual( set(response.context['form'].fields), set(get_document_model().admin_form_fields) - {'file', 'collection'}, ) self.assertEqual(response.context['form'].initial['title'], 'test.png') # Check JSON response_json = json.loads(response.content.decode()) self.assertIn('doc_id', response_json) self.assertIn('form', response_json) self.assertIn('success', response_json) self.assertEqual(response_json['doc_id'], response.context['doc'].id) self.assertTrue(response_json['success']) # form should not contain a collection chooser self.assertNotIn('Collection', response_json['form'])
def test_get_video_with_collections(self): root_collection = Collection.get_first_root_node() root_collection.add_child(name="Evil plans") response = self.client.get( reverse('wagtailmedia:add', args=('video', ))) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailmedia/media/add.html') self.assertContains(response, '<label for="id_collection">') self.assertContains(response, "Evil plans") self.assertContains(response, 'Add video') self.assertContains( response, '<form action="{0}" method="POST" enctype="multipart/form-data" novalidate>' .format(reverse('wagtailmedia:add', args=('video', ))), count=1)
def get_chooser_context(request): """Helper function to return common template context variables for the main chooser view""" collections = Collection.objects.all() if len(collections) < 2: collections = None else: collections = Collection.order_for_display(collections) return { 'searchform': SearchForm(), 'is_searching': False, 'query_string': None, 'will_select_format': request.GET.get('select_format'), 'popular_tags': popular_tags_for_model(get_image_model()), 'collections': collections, }
def test_nested_ordering(self): root_collection = Collection.get_first_root_node() vegetables = root_collection.add_child(name="Vegetable") vegetables.add_child(name="Spinach") vegetables.add_child(name="Cucumber") animals = root_collection.add_child(name="Animal") animals.add_child(name="Dog") animals.add_child(name="Cat") response = self.get() # Note that while we added the collections at level 1 in reverse-alpha order, they come back out in alpha order. # And we added the Collections at level 2 in reverse-alpha order as well, but they were also alphabetized # within their respective trees. This is the result of setting Collection.node_order_by = ['name']. self.assertEqual([ collection.name for collection in response.context['object_list'] ], ['Animal', 'Cat', 'Dog', 'Vegetable', 'Cucumber', 'Spinach'])
def test_simple(self): response = self.get() self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/collections/index.html') # Initially there should be no collections listed # (Root should not be shown) self.assertContains(response, "No collections have been created.") root_collection = Collection.get_first_root_node() self.collection = root_collection.add_child(name="Holiday snaps") # Now the listing should contain our collection response = self.get() self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/collections/index.html') self.assertNotContains(response, "No collections have been created.") self.assertContains(response, "Holiday snaps")
def test_get_video_with_collections(self): root_collection = Collection.get_first_root_node() root_collection.add_child(name="Evil plans") response = self.client.get(reverse('wagtailmedia:add', args=('video', ))) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailmedia/media/add.html') self.assertContains(response, '<label for="id_collection">') self.assertContains(response, "Evil plans") self.assertContains(response, 'Add video') self.assertContains( response, '<form action="{0}" method="POST" enctype="multipart/form-data" novalidate>'.format( reverse('wagtailmedia:add', args=('video',)) ), count=1 )
def setUp(self): self.user = self.login() self.root_collection = Collection.get_first_root_node() self.dest_collection = self.root_collection.add_child( name="Destination") self.images = [ Image.objects.create(title=f"Test image - {i}", file=test_file) for i in range(1, 6) ] self.url = reverse('wagtail_bulk_action', args=( 'wagtailimages', 'image', 'add_to_collection', )) + '?' for image in self.images: self.url += f'id={image.id}&' self.post_data = {'collection': str(self.dest_collection.id)}
def test_add_with_collections(self): root_collection = Collection.get_first_root_node() evil_plans_collection = root_collection.add_child(name="Evil plans") response = self.post({ 'title': "Test image", 'file': SimpleUploadedFile('test.png', get_test_image_file().file.getvalue()), 'collection': evil_plans_collection.id, }) # Should redirect back to index self.assertRedirects(response, reverse('wagtailimages:index')) # Check that the image was created images = Image.objects.filter(title="Test image") self.assertEqual(images.count(), 1) # Test that it was placed in the Evil Plans collection image = images.first() self.assertEqual(image.collection, evil_plans_collection)
def test_add_with_collections(self): root_collection = Collection.get_first_root_node() evil_plans_collection = root_collection.add_child(name="Evil plans") response = self.post({ 'title': "Test video", 'file': SimpleUploadedFile('small.mp4', create_test_video_file().read(), "video/mp4"), 'collection': evil_plans_collection.id, }) # Should redirect back to index self.assertRedirects(response, reverse('wagtailvideos:index')) # Check that the video was created videos = Video.objects.filter(title="Test video") self.assertEqual(videos.count(), 1) # Test that it was placed in the Evil Plans collection video = videos.first() self.assertEqual(video.collection, evil_plans_collection)
def test_post_audio(self): # Build a fake file fake_file = ContentFile(b("A boring example song"), name="song.mp3") # Submit post_data = {"title": "Test media", "file": fake_file, "duration": 100} response = self.client.post( reverse("wagtailmedia:add", args=("audio", )), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse("wagtailmedia:index")) # Media should be created, and be placed in the root collection self.assertTrue( models.Media.objects.filter(title="Test media").exists()) root_collection = Collection.get_first_root_node() media = models.Media.objects.get(title="Test media") self.assertEqual(media.collection, root_collection) self.assertEqual(media.type, "audio")
def setUp(self): self.user = self.login() self.root_collection = Collection.get_first_root_node() self.dest_collection = self.root_collection.add_child(name="Destination") self.documents = [ Document.objects.create(title=f"Test document - {i}") for i in range(1, 6) ] self.url = ( reverse( "wagtail_bulk_action", args=( "wagtaildocs", "document", "add_to_collection", ), ) + "?" ) for document in self.documents: self.url += f"id={document.id}&" self.post_data = {"collection": str(self.dest_collection.id)}
def setUp(self): self.user = self.login() self.root_collection = Collection.get_first_root_node() self.dest_collection = self.root_collection.add_child(name="Destination") self.images = [ Image.objects.create(title=f"Test image - {i}", file=test_file) for i in range(1, 6) ] self.url = ( reverse( "wagtail_bulk_action", args=( "wagtailimages", "image", "add_to_collection", ), ) + "?" ) for image in self.images: self.url += f"id={image.id}&" self.post_data = {"collection": str(self.dest_collection.id)}
def test_as_ordinary_editor(self): user = get_user_model().objects.create_user(username='******', email='*****@*****.**', password='******') add_permission = Permission.objects.get( content_type__app_label='wagtailimages', codename='add_image') admin_permission = Permission.objects.get( content_type__app_label='wagtailadmin', codename='access_admin') image_adders_group = Group.objects.create(name='Image adders') image_adders_group.permissions.add(admin_permission) GroupCollectionPermission.objects.create( group=image_adders_group, collection=Collection.get_first_root_node(), permission=add_permission) user.groups.add(image_adders_group) self.client.login(username='******', password='******') response = self.client.get(reverse('wagtailimages:add_multiple')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailimages/multiple/add.html')
def test_post(self): # Build a fake file fake_file = get_test_document_file() # Submit post_data = { 'title': "Test document", 'file': fake_file, } response = self.client.post(reverse('wagtaildocs:add'), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtaildocs:index')) # Document should be created, and be placed in the root collection document = models.Document.objects.get(title="Test document") root_collection = Collection.get_first_root_node() self.assertEqual(document.collection, root_collection) # Check that the file_size/hash field was set self.assertTrue(document.file_size) self.assertTrue(document.file_hash)
def test_post(self): # Build a fake file fake_file = ContentFile(b("A boring example document")) fake_file.name = 'test.txt' # Submit post_data = { 'title': "Test document", 'file': fake_file, } response = self.client.post(reverse('wagtaildocs:add'), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtaildocs:index')) # Document should be created, and be placed in the root collection self.assertTrue( models.Document.objects.filter(title="Test document").exists()) root_collection = Collection.get_first_root_node() self.assertEqual( models.Document.objects.get(title="Test document").collection, root_collection)
def setUp(self): # Build a fake file fake_file = ContentFile(b("A boring example song")) fake_file.name = "song.mp3" self.root_collection = Collection.get_first_root_node() self.evil_plans_collection = self.root_collection.add_child( name="Evil plans") self.nice_plans_collection = self.root_collection.add_child( name="Nice plans") # Create a media to edit self.media = models.Media.objects.create( title="Test media", file=fake_file, collection=self.nice_plans_collection, duration=100, ) # Create a user with change_media permission but not add_media user = get_user_model().objects.create_user( username="******", email="*****@*****.**", password="******") change_permission = Permission.objects.get( content_type__app_label="wagtailmedia", codename="change_media") admin_permission = Permission.objects.get( content_type__app_label="wagtailadmin", codename="access_admin") self.changers_group = Group.objects.create(name="Media changers") GroupCollectionPermission.objects.create( group=self.changers_group, collection=self.root_collection, permission=change_permission, ) user.groups.add(self.changers_group) user.user_permissions.add(admin_permission) self.assertTrue( self.client.login(username="******", password="******"))
def test_post_audio(self): # Build a fake file fake_file = ContentFile(b("A boring example song")) fake_file.name = 'song.mp3' # Submit post_data = { 'title': "Test media", 'file': fake_file, 'duration': 100, } response = self.client.post(reverse('chunked_media:add', args=('audio', )), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('chunked_media:index')) # Media should be created, and be placed in the root collection self.assertTrue(models.Media.objects.filter(title="Test media").exists()) root_collection = Collection.get_first_root_node() media = models.Media.objects.get(title="Test media") self.assertEqual(media.collection, root_collection) self.assertEqual(media.type, 'audio')
def setUp(self): # Create some user accounts for testing permissions User = get_user_model() self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.owner = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.editor = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.editor.groups.add(Group.objects.get(name='Editors')) self.administrator = User.objects.create_superuser( username='******', email='*****@*****.**', password='******' ) # Owner user must have the add_media permission self.adders_group = Group.objects.create(name='Media adders') GroupCollectionPermission.objects.create( group=self.adders_group, collection=Collection.get_first_root_node(), permission=Permission.objects.get(codename='add_media') ) self.owner.groups.add(self.adders_group) # Create a media for running tests on self.media = models.Media.objects.create(title="Test media", duration=100, uploaded_by_user=self.owner)
def test_post_audio(self): # Build a fake file fake_file = ContentFile(b("A boring example song")) fake_file.name = 'song.mp3' # Submit post_data = { 'title': "Test media", 'file': fake_file, 'duration': 100, } response = self.client.post(reverse('wagtailmedia:add', args=('audio', )), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse('wagtailmedia:index')) # Media should be created, and be placed in the root collection self.assertTrue(models.Media.objects.filter(title="Test media").exists()) root_collection = Collection.get_first_root_node() media = models.Media.objects.get(title="Test media") self.assertEqual(media.collection, root_collection) self.assertEqual(media.type, 'audio')
def __init__(self): with open('importer/log/import_media_files.txt', 'w') as log: log.write('errors found while importing media files\n') images = Image.objects.all() documents = Document.objects.all() if images or documents: sys.stdout.write( '⚠️ Run delete_media_files before running this command\n') sys.exit() else: # keep it tidy remove collections first always for key in SOURCES.keys(): try: collection = Collection.objects.filter(name=SOURCES[key]) for c in collection: c.delete() sys.stdout.write('-') except Collection.DoesNotExist: pass # make collections based on sources collection_root = Collection.get_first_root_node() for key in SOURCES.keys(): collection_root.add_child(name=SOURCES[key])
def setUp(self) -> None: self.user = get_custom_user(username='******', password='******') Token.objects.create(user=self.user) self.client = RequestsClient() api_group = Group.objects.create(name="API") self.user.groups.add(api_group) # Create wagtail collection used during image upload view root_coll = WagtailCollection.get_first_root_node() root_coll.add_child(name='BRAHMS Data') self.family = get_family() self.genus = get_genus(self.family) self.species = get_species(self.genus) token_url = self.live_server_url + reverse('plants:api-token') response = self.client.post(token_url, data={ 'username': '******', 'password': '******' }) token = {'drf_token': response.json()['token']} self.client.headers.update({ 'Accept': 'application/json; q=1.0, */*', 'Authorization': 'Token ' + token['drf_token'] }) self.img_file_obj = BytesIO() image_one = Image.new('RGB', size=(1, 1), color=(256, 0, 0)) image_one.save(self.img_file_obj, 'jpeg') self.img_file_obj.seek(0) self.img_one = ImageFile(self.img_file_obj, name='1.jpg')
def test_add_post(self): """ This tests that a POST request to the add view saves the document and returns an edit form """ response = self.client.post(reverse('wagtaildocs:add_multiple'), { 'files[]': SimpleUploadedFile('test.png', b"Simple text document"), }, HTTP_X_REQUESTED_WITH='XMLHttpRequest') # Check response self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertTemplateUsed(response, 'wagtaildocs/multiple/edit_form.html') # Check document self.assertIn('doc', response.context) self.assertEqual(response.context['doc'].title, 'test.png') self.assertTrue(response.context['doc'].file_size) # check that it is in the root collection doc = models.Document.objects.get(title='test.png') root_collection = Collection.get_first_root_node() self.assertEqual(doc.collection, root_collection) # Check form self.assertIn('form', response.context) self.assertEqual(response.context['form'].initial['title'], 'test.png') # Check JSON response_json = json.loads(response.content.decode()) self.assertIn('doc_id', response_json) self.assertIn('form', response_json) self.assertIn('success', response_json) self.assertEqual(response_json['doc_id'], response.context['doc'].id) self.assertTrue(response_json['success']) # form should not contain a collection chooser self.assertNotIn('Collection', response_json['form'])
def setUp(self): # Create an image to edit self.image = Image.objects.create( title="Test image", file=get_test_image_file(), ) # Create a user with change_image permission but not add_image user = get_user_model().objects.create_user( username='******', email='*****@*****.**', password='******' ) change_permission = Permission.objects.get(content_type__app_label='wagtailimages', codename='change_image') admin_permission = Permission.objects.get(content_type__app_label='wagtailadmin', codename='access_admin') image_changers_group = Group.objects.create(name='Image changers') image_changers_group.permissions.add(admin_permission) GroupCollectionPermission.objects.create( group=image_changers_group, collection=Collection.get_first_root_node(), permission=change_permission ) user.groups.add(image_changers_group) self.assertTrue(self.client.login(username='******', password='******'))
def test_post_video_with_collections(self): root_collection = Collection.get_first_root_node() evil_plans_collection = root_collection.add_child(name="Evil plans") # Submit post_data = { "title": "Test media", "file": ContentFile(b("A boring example movie"), name="movie.mp4"), "duration": 100, "collection": evil_plans_collection.id, } response = self.client.post( reverse("wagtailmedia:add", args=("video", )), post_data) # User should be redirected back to the index self.assertRedirects(response, reverse("wagtailmedia:index")) # Media should be created, and be placed in the Evil Plans collection self.assertTrue( models.Media.objects.filter(title="Test media").exists()) media = models.Media.objects.get(title="Test media") self.assertEqual(media.collection, evil_plans_collection) self.assertEqual(media.type, "video")
def setUp(self): # Build a fake file fake_file = ContentFile(b("A boring example document")) fake_file.name = 'test.txt' self.root_collection = Collection.get_first_root_node() self.evil_plans_collection = self.root_collection.add_child( name="Evil plans") self.nice_plans_collection = self.root_collection.add_child( name="Nice plans") # Create a document to edit self.document = models.Document.objects.create( title="Test document", file=fake_file, collection=self.nice_plans_collection) # Create a user with change_document permission but not add_document user = get_user_model().objects.create_user( username='******', email='*****@*****.**', password='******') change_permission = Permission.objects.get( content_type__app_label='wagtaildocs', codename='change_document') admin_permission = Permission.objects.get( content_type__app_label='wagtailadmin', codename='access_admin') self.changers_group = Group.objects.create(name='Document changers') GroupCollectionPermission.objects.create( group=self.changers_group, collection=self.root_collection, permission=change_permission) user.groups.add(self.changers_group) user.user_permissions.add(admin_permission) self.assertTrue( self.client.login(username='******', password='******'))
def test_add(self): response = self.post({ 'title': "Test image", 'file': SimpleUploadedFile('test.png', get_test_image_file().file.getvalue()), }) # Should redirect back to index self.assertRedirects(response, reverse('wagtailimages:index')) # Check that the image was created images = Image.objects.filter(title="Test image") self.assertEqual(images.count(), 1) # Test that size was populated correctly image = images.first() self.assertEqual(image.width, 640) self.assertEqual(image.height, 480) # Test that the file_size field was set self.assertTrue(image.file_size) # Test that it was placed in the root collection root_collection = Collection.get_first_root_node() self.assertEqual(image.collection, root_collection)
def setUp(self): add_media_permission = Permission.objects.get( content_type__app_label='wagtailmedia', codename='add_media') admin_permission = Permission.objects.get( content_type__app_label='wagtailadmin', codename='access_admin') root_collection = Collection.get_first_root_node() self.evil_plans_collection = root_collection.add_child( name="Evil plans") conspirators_group = Group.objects.create(name="Evil conspirators") conspirators_group.permissions.add(admin_permission) GroupCollectionPermission.objects.create( group=conspirators_group, collection=self.evil_plans_collection, permission=add_media_permission) user = get_user_model().objects.create_user( username='******', email='*****@*****.**', password='******') user.groups.add(conspirators_group) self.client.login(username='******', password='******')
def index(request): Document = get_document_model() # Get documents (filtered by user permission) documents = permission_policy.instances_user_has_any_permission_for( request.user, ['change', 'delete'] ) # Ordering if 'ordering' in request.GET and request.GET['ordering'] in ['title', '-created_at']: ordering = request.GET['ordering'] else: ordering = '-created_at' documents = documents.order_by(ordering) # Filter by collection current_collection = None collection_id = request.GET.get('collection_id') if collection_id: try: current_collection = Collection.objects.get(id=collection_id) documents = documents.filter(collection=current_collection) except (ValueError, Collection.DoesNotExist): pass # Search query_string = None if 'q' in request.GET: form = SearchForm(request.GET, placeholder=_("Search documents")) if form.is_valid(): query_string = form.cleaned_data['q'] documents = documents.search(query_string) else: form = SearchForm(placeholder=_("Search documents")) # Pagination paginator = Paginator(documents, per_page=20) documents = paginator.get_page(request.GET.get('p')) collections = permission_policy.collections_user_has_any_permission_for( request.user, ['add', 'change'] ) if len(collections) < 2: collections = None else: collections = Collection.order_for_display(collections) # Create response if request.is_ajax(): return render(request, 'wagtaildocs/documents/results.html', { 'ordering': ordering, 'documents': documents, 'query_string': query_string, 'is_searching': bool(query_string), }) else: return render(request, 'wagtaildocs/documents/index.html', { 'ordering': ordering, 'documents': documents, 'query_string': query_string, 'is_searching': bool(query_string), 'search_form': form, 'popular_tags': popular_tags_for_model(Document), 'user_can_add': permission_policy.user_has_permission(request.user, 'add'), 'collections': collections, 'current_collection': current_collection, })
def chooser(request): Document = get_document_model() if permission_policy.user_has_permission(request.user, 'add'): DocumentForm = get_document_form(Document) uploadform = DocumentForm(user=request.user) else: uploadform = None documents = Document.objects.all() # allow hooks to modify the queryset for hook in hooks.get_hooks('construct_document_chooser_queryset'): documents = hook(documents, request) q = None if 'q' in request.GET or 'p' in request.GET or 'collection_id' in request.GET: collection_id = request.GET.get('collection_id') if collection_id: documents = documents.filter(collection=collection_id) documents_exist = documents.exists() searchform = SearchForm(request.GET) if searchform.is_valid(): q = searchform.cleaned_data['q'] documents = documents.search(q) is_searching = True else: documents = documents.order_by('-created_at') is_searching = False # Pagination paginator = Paginator(documents, per_page=10) documents = paginator.get_page(request.GET.get('p')) return render(request, "wagtaildocs/chooser/results.html", { 'documents': documents, 'documents_exist': documents_exist, 'uploadform': uploadform, 'query_string': q, 'is_searching': is_searching, 'collection_id': collection_id, }) else: searchform = SearchForm() collections = Collection.objects.all() if len(collections) < 2: collections = None else: collections = Collection.order_for_display(collections) documents = documents.order_by('-created_at') documents_exist = documents.exists() paginator = Paginator(documents, per_page=10) documents = paginator.get_page(request.GET.get('p')) return render_modal_workflow(request, 'wagtaildocs/chooser/chooser.html', None, { 'documents': documents, 'documents_exist': documents_exist, 'uploadform': uploadform, 'searchform': searchform, 'collections': collections, 'is_searching': False, }, json_data=get_chooser_context())