Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bulk delete action #317

Merged
merged 2 commits into from
Sep 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions sqladmin/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ def http_exception(request: Request, exc: Exception) -> Response:
Route("/{identity}/list", endpoint=self.list, name="list"),
Route("/{identity}/details/{pk}", endpoint=self.details, name="details"),
Route(
"/{identity}/delete/{pk}",
"/{identity}/delete",
endpoint=self.delete,
name="delete",
methods=["DELETE"],
Expand Down Expand Up @@ -398,11 +398,13 @@ async def delete(self, request: Request) -> Response:
identity = request.path_params["identity"]
model_view = self._find_model_view(identity)

model = await model_view.get_model_by_pk(request.path_params["pk"])
if not model:
raise HTTPException(status_code=404)
pks = request.query_params.get("pks", "")
for pk in pks.split(","):
model = await model_view.get_model_by_pk(pk)
if not model:
raise HTTPException(status_code=404)

await model_view.delete_model(model)
await model_view.delete_model(model)

return Response(content=request.url_for("admin:list", identity=identity))

Expand Down
9 changes: 5 additions & 4 deletions sqladmin/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
Union,
no_type_check,
)
from urllib.parse import urlencode

import anyio
from sqlalchemy import Column, asc, desc, func, inspect, or_
Expand Down Expand Up @@ -718,11 +719,11 @@ def _url_for_edit(self, obj: Any) -> str:

def _url_for_delete(self, obj: Any) -> str:
pk = getattr(obj, get_primary_key(obj).name)
return self.url_path_for(
"admin:delete",
identity=slugify_class_name(obj.__class__.__name__),
pk=pk,
query_params = urlencode({"pks": pk})
url = self.url_path_for(
"admin:delete", identity=slugify_class_name(obj.__class__.__name__)
)
return url + "?" + query_params

def _url_for_details_with_attr(self, obj: Any, attr: RelationshipProperty) -> str:
target = getattr(obj, attr.key)
Expand Down
26 changes: 26 additions & 0 deletions sqladmin/statics/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,29 @@ $(':input[data-role="select2-ajax"]').each(function () {
$(this).append(option).trigger('change');
}
});

// Checkbox select
$("#select-all").click(function () {
var checked = $(this).is(':checked');
$('.select-box').each(function () {
$(this).attr("checked", checked);
});
});

// Bulk delete
$("#action-delete").click(function () {
var pks = [];
$('.select-box').each(function () {
if ($(this).is(':checked')) {
pks.push($(this).parent().siblings().get(0).value);
}
});

$.ajax({
url: $(this).attr('data-url') + '?pks=' + pks.join(","),
method: 'DELETE',
success: function (result) {
window.location.href = result;
}
});
});
2 changes: 1 addition & 1 deletion sqladmin/templates/details.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ <h3 class="card-title">{{ model_view.pk_column.name }}: {{ model_view.get_attr_v
</div>
<div class="card-body border-bottom py-3">
<div class="table-responsive">
<table class="table card-table table-vcenter text-nowrap datatable table-hover table-bordered">
<table class="table card-table table-vcenter text-nowrap table-hover table-bordered">
<thead>
<tr>
<th class="w-1">Column</th>
Expand Down
19 changes: 14 additions & 5 deletions sqladmin/templates/list.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ <h3 class="card-title">{{ model_view.name_plural }}</h3>
</div>
<div class="card-body border-bottom py-3">
<div class="d-flex">
<div class="dropdown text-muted">
<div class="dropdown text-muted col-4">
Show
<a href="#" class="btn btn-light dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ request.query_params.get("pageSize") or model_view.page_size }}
Expand All @@ -50,8 +50,16 @@ <h3 class="card-title">{{ model_view.name_plural }}</h3>
{% endfor %}
</div>
</div>
<div class="dropdown col-4">
<button class="btn btn-light dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Actions
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" id="action-delete" href="#" data-url="{{ url_for('admin:delete', identity=model_view.identity) }}">Delete selected items</a>
</div>
</div>
{% if model_view.column_searchable_list %}
<div class="ms-auto text-muted">
<div class="col-md-4 text-muted">
<div class="input-group ms-2">
<input id="search-input" type="text" class="form-control" placeholder="Search: {{ model_view.search_placeholder() }}" value="{{ request.query_params.get('search', '') }}">
<button id="search-button" class="btn" type="button">Search</button>
Expand All @@ -62,10 +70,10 @@ <h3 class="card-title">{{ model_view.name_plural }}</h3>
</div>
</div>
<div class="table-responsive">
<table class="table card-table table-vcenter text-nowrap datatable">
<table class="table card-table table-vcenter text-nowrap">
<thead>
<tr>
<th class="w-1"><input class="form-check-input m-0 align-middle" type="checkbox" aria-label="Select all"></th>
<th class="w-1"><input class="form-check-input m-0 align-middle" type="checkbox" aria-label="Select all" id="select-all"></th>
<th class="w-1"></th>
{% for name, attr in model_view._list_attrs %}
<th>
Expand All @@ -87,7 +95,8 @@ <h3 class="card-title">{{ model_view.name_plural }}</h3>
<tbody>
{% for row in pagination.rows %}
<tr>
<td><input class="form-check-input m-0 align-middle" type="checkbox" aria-label="Select item"></td>
<input type="hidden" value="{{ model_view.get_attr_value(row, model_view.pk_column) }}">
<td><input class="form-check-input m-0 align-middle select-box" type="checkbox" aria-label="Select item"></td>
<td class="text-end">
{% if model_view.can_view_details %}
<a href="{{ model_view._url_for_details(row) }}" data-bs-toggle="tooltip" data-bs-placement="top" title="View">
Expand Down
6 changes: 3 additions & 3 deletions tests/test_admin_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,13 +423,13 @@ async def test_column_labels(client: AsyncClient) -> None:


async def test_delete_endpoint_unauthorized_response(client: AsyncClient) -> None:
response = await client.delete("/admin/movie/delete/1")
response = await client.delete("/admin/movie/delete")

assert response.status_code == 403


async def test_delete_endpoint_not_found_response(client: AsyncClient) -> None:
response = await client.delete("/admin/user/delete/1")
response = await client.delete("/admin/user/delete?pks=1")

assert response.status_code == 404

Expand All @@ -451,7 +451,7 @@ async def test_delete_endpoint(client: AsyncClient) -> None:
result = await s.execute(stmt)
assert result.scalar_one() == 1

response = await client.delete("/admin/user/delete/1")
response = await client.delete("/admin/user/delete?pks=1")

assert response.status_code == 200

Expand Down
6 changes: 3 additions & 3 deletions tests/test_admin_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,13 +416,13 @@ def test_column_labels(client: TestClient) -> None:


def test_delete_endpoint_unauthorized_response(client: TestClient) -> None:
response = client.delete("/admin/movie/delete/1")
response = client.delete("/admin/movie/delete")

assert response.status_code == 403


def test_delete_endpoint_not_found_response(client: TestClient) -> None:
response = client.delete("/admin/user/delete/1")
response = client.delete("/admin/user/delete?pks=1")

assert response.status_code == 404

Expand All @@ -438,7 +438,7 @@ def test_delete_endpoint(client: TestClient) -> None:
with LocalSession() as s:
assert s.query(User).count() == 1

response = client.delete("/admin/user/delete/1")
response = client.delete("/admin/user/delete?pks=1")

assert response.status_code == 200

Expand Down