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 support for primary filters in CRUDView #79

Merged
merged 3 commits into from
Jul 26, 2024
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ and this project attempts to adhere to [Semantic Versioning](https://semver.org/

## [Unreleased]

### Added

- Added support for specifying primary filters on `CRUDView` via a `filterset_primary_fields` class attribute. Sometimes you have a model and corresponding crud view that has a bunch of filters attached to it. Rather than show all filters or show none and hide them behind a 'Show Filters' button, this allows you to have a handful of primary filters with the rest of the filters set as secondary. This way, you can always show the primary filters, but hide the secondary ones.

### Changed

- Added override of `get_paginate_by` to `CRUDView` in order to accept arbitrary `args` and `kwargs`. This is due to the differences in the method between `neapolitan.views.CRUDView` and `django_tables2.views.SingleTableMixin`. By making this change, it simplifies the code path in the `CRUDView.list` method a tiny bit.
Expand Down
22 changes: 21 additions & 1 deletion src/django_twc_toolbox/crud/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import Literal

from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.http import Http404
from django.http import HttpRequest
from django.http import HttpResponse
Expand Down Expand Up @@ -57,6 +58,8 @@ class CRUDView(NeapolitanCRUDView):
# at least for the time being.
list_partial: ClassVar[Literal["object-list"]] = "object-list"

filterset_primary_fields: list[str] | None = None

request: HtmxHttpRequest # pyright: ignore[reportIncompatibleVariableOverride]

def get_fields(self):
Expand Down Expand Up @@ -93,7 +96,7 @@ def list(

filterset = self.get_filterset(queryset)
if filterset is not None:
queryset = filterset.qs
queryset = filterset.qs # type:ignore[attr-defined]

if not self.allow_empty and not queryset.exists():
raise Http404
Expand Down Expand Up @@ -124,6 +127,23 @@ def list(
def get_paginate_by(self, *args: object, **kwargs: object) -> int | None:
return super().get_paginate_by()

@override
def get_filterset(
self, queryset: models.QuerySet[models.Model] | None = None
) -> object | None:
filterset = super().get_filterset(queryset)

if filterset is None:
return None

if self.filterset_primary_fields is not None:
filterset.primary_fields = self.filterset_primary_fields # type: ignore[attr-defined]
filterset.secondary_fields = list( # type: ignore[attr-defined]
set(filterset.form.fields.keys()) - set(filterset.primary_fields) # type:ignore[attr-defined]
)

return filterset

@override
def get_context_data(self, **kwargs: object) -> dict[str, object]:
context = super().get_context_data(**kwargs)
Expand Down
3 changes: 1 addition & 2 deletions src/stubs/neapolitan/views.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import enum
from collections.abc import Callable
from collections.abc import Iterable
from collections.abc import Mapping
from typing import Any # pyright: ignore[reportAny]
from typing import ClassVar
from typing import List
from typing import TypeVar
Expand Down Expand Up @@ -107,7 +106,7 @@ class CRUDView(View):
def get_filterset(
self,
queryset: models.QuerySet[models.Model] | None = None,
) -> Any: ... # TODO: change Any to FilterSet
) -> _TObject: ... # TODO: change Any to FilterSet
def get_context_object_name(self, is_list: bool = False) -> str | None: ...
def get_context_data(self, **kwargs: _TObject) -> dict[str, _TObject]: ...
def get_template_names(self) -> List[str]: ...
Expand Down
18 changes: 18 additions & 0 deletions tests/test_crud/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,21 @@ def test_table_view_ordered(client, db):
response = client.get(Role.LIST.maybe_reverse(BookmarkTableOrderedView))

assert response.status_code == 200


def test_filterset_primary_fields(rf):
class BookmarkFilterSetPrimaryFieldsView(BookmarkView):
filterset_fields = ["url", "title", "note"]
filterset_primary_fields = ["url"]

request = rf.get(Role.LIST.maybe_reverse(BookmarkView))

view = BookmarkFilterSetPrimaryFieldsView(
role=Role.LIST, **Role.LIST.extra_initkwargs()
)
view.setup(request)

filterset = view.get_filterset()

assert set(filterset.primary_fields) == {"url"}
assert set(filterset.secondary_fields) == {"title", "note"}