mirror of
https://github.com/netbox-community/netbox.git
synced 2026-01-19 01:58:43 -06:00
Some checks failed
CI / build (20.x, 3.12) (push) Has been cancelled
CI / build (20.x, 3.13) (push) Has been cancelled
CodeQL / Analyze (${{ matrix.language }}) (none, actions) (push) Has been cancelled
CodeQL / Analyze (${{ matrix.language }}) (none, javascript-typescript) (push) Has been cancelled
CodeQL / Analyze (${{ matrix.language }}) (none, python) (push) Has been cancelled
* Fixes #7604: Add filter modifier dropdowns for advanced lookup operators Implements dynamic filter modifier UI that allows users to select lookup operators (exact, contains, starts with, regex, negation, empty/not empty) directly in filter forms without manual URL parameter editing. Supports filters for all scalar types and strings, as well as some related object filters. Explicitly does not support filters on fields that use APIWidget. That has been broken out in to follow up work. **Backend:** - FilterModifierWidget: Wraps form widgets with lookup modifier dropdown - FilterModifierMixin: Auto-enhances filterset fields with appropriate lookups - Extended lookup support: Adds negation (n), regex, iregex, empty_true/false lookups - Field-type-aware: CharField gets text lookups, IntegerField gets comparison operators, etc. **Frontend:** - TypeScript handler syncs modifier dropdown with URL parameters - Dynamically updates form field names (serial → serial__ic) on modifier change - Flexible-width modifier dropdowns with semantic CSS classes * Remove extraneous TS comments * Fix import order * Fix CircuitFilterForm inheritance * Enable filter form modifiers on DCIM models * Enable filter form modifiers on Tenancy models * Enable filter form modifiers on Wireless models * Enable filter form modifiers on IPAM models * Enable filter form modifiers on VPN models * Enable filter form modifiers on Virtualization models * Enable filter form modifiers on Circuit models * Enable filter form modifiers on Users models * Enable filter form modifiers on Core models * Enable filter form modifiers on Extras models * Add ChoiceField support to FilterModifierMixin Enable filter modifiers for single-choice ChoiceFields in addition to the existing MultipleChoiceField support. ChoiceFields can now display modifier dropdowns with "Is", "Is Not", "Is Empty", and "Is Not Empty" options when the corresponding FilterSet defines those lookups. The mixin correctly verifies lookup availability against the FilterSet, so modifiers only appear when multiple lookup options are actually supported. Currently most FilterSets only define 'exact' for single-choice fields, but this change enables future FilterSet enhancements to expose additional lookups for ChoiceFields. * Address PR feedback: Replace global filterset mappings with registry * Address PR feedback: Move FilterModifierMixin into base filter form classes Incorporates FilterModifierMixin into NetBoxModelFilterSetForm and FilterForm, making filter modifiers automatic for all filter forms throughout the application. * Fix filter modifier form submission bug with 'action' field collision Forms with a field named "action" (e.g., ObjectChangeFilterForm) were causing the form.action property to be shadowed by the field element, resulting in [object HTMLSelectElement] appearing in the URL path. Use form.getAttribute('action') instead of form.action to reliably retrieve the form's action URL without collision from form fields. Fixes form submission on /core/changelog/ and any other forms with an 'action' field using filter modifiers. * Address PR feedback: Move FORM_FIELD_LOOKUPS to module-level constant Extracts the field type to lookup mappings from FilterModifierMixin class attribute to a module-level constant for better reusability. * Address PR feedback: Refactor and consolidate field filtering logic Consolidated field enhancement logic in FilterModifierMixin by: - Creating QueryField marker type (CharField subclass) for search fields - Updating FilterForm and NetBoxModelFilterSetForm to use QueryField for 'q' - Moving all skip logic into _get_lookup_choices() to return empty list for fields that shouldn't be enhanced - Removing separate _should_skip_field() method - Removing unused field_name parameter from _get_lookup_choices() - Replacing hardcoded field name check ('q') with type-based detection * Address PR feedback: Refactor applied_filters to use FORM_FIELD_LOOKUPS * Address PR feedback: Rename FilterModifierWidget parameter to widget * Fix registry pattern to use model identifiers as keys Changed filterset registration to use model identifiers ('{app_label}.{model_name}') as registry keys instead of form classes, matching NetBox's pattern for search indexes. * Address PR feedback: refactor brittle test for APISelect useage Now checks if widget is actually APISelect, rather than trying to infer from the class name. * Refactor register_filterset to be more generic and simple * Remove unneeded imports left from earlier registry work * Update app registry for new `filtersets` store * Remove unused star import, leftover from earlier work * Enables filter modifiers on APISelect based fields * Support filter modifiers for ChoiceField * Include MODIFIER_EMPTY_FALSE/_TRUE in __all__ Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com> * Fix filterset registration for doubly-registered models * Removed explicit checks against QueryField and [Null]BooleanField I did add them to FORM_FIELD_LOOKUPS, though, to underscore that they were considered and are intentially empty for future devs. * Switch to sentence case for filter pill text * Fix applied_filters template tag to use field-type-specific lookup labelsresolves E.g. resolves gt="after" for dates vs "greater than" for numbers * Verifies that filter pills for exact matches (no lookup Add test for exact lookup filter pill rendering * Add guard for FilterModifierWidget with no lookups * Remove comparison symbols from numeric filter labels * Match complete tags in widget rendering test assertions * Check all expected lookups in field enhancement tests * Move register_filterset to netbox.plugins.registration * Require registered filterset for filter modifier enhancements Updates FilterModifierMixin to only enhance form fields when the associated model has a registered filterset. This provides plugin safety by ensuring unregistered plugin filtersets fall back to simple filters without lookup modifiers. Test changes: - Create TestModel and TestFilterSet using BaseFilterSet for automatic lookup generation - Import dcim.filtersets to ensure Device filterset registration - Adjust tag field expectations to match actual Device filterset (has exact/n but not empty lookups) * Attempt to resolve static conflicts * Move register_filterset() back to utilities.filtersets * Add register_filterset() to plugins documentation for filtersets * Reorder import statements --------- Co-authored-by: Jeremy Stretch <jstretch@netboxlabs.com>
114 lines
4.4 KiB
Python
114 lines
4.4 KiB
Python
from django import forms
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
|
__all__ = (
|
|
'FilterModifierWidget',
|
|
'MODIFIER_EMPTY_FALSE',
|
|
'MODIFIER_EMPTY_TRUE',
|
|
)
|
|
|
|
# Modifier codes for empty/null checking
|
|
# These map to Django's 'empty' lookup: field__empty=true/false
|
|
MODIFIER_EMPTY_TRUE = 'empty_true'
|
|
MODIFIER_EMPTY_FALSE = 'empty_false'
|
|
|
|
|
|
class FilterModifierWidget(forms.Widget):
|
|
"""
|
|
Wraps an existing widget to add a modifier dropdown for filter lookups.
|
|
|
|
The original widget's semantics (name, id, attributes) are preserved.
|
|
The modifier dropdown controls which lookup type is used (exact, contains, etc.).
|
|
"""
|
|
template_name = 'widgets/filter_modifier.html'
|
|
|
|
def __init__(self, widget, lookups, attrs=None):
|
|
"""
|
|
Args:
|
|
widget: The widget being wrapped (e.g., TextInput, NumberInput)
|
|
lookups: List of (lookup_code, label) tuples (e.g., [('exact', 'Is'), ('ic', 'Contains')])
|
|
attrs: Additional widget attributes
|
|
"""
|
|
self.original_widget = widget
|
|
self.lookups = lookups
|
|
super().__init__(attrs or getattr(widget, 'attrs', {}))
|
|
|
|
def value_from_datadict(self, data, files, name):
|
|
"""
|
|
Extract value from data, checking all possible lookup variants.
|
|
|
|
When form redisplays after validation error, the data may contain
|
|
serial__ic=test but the field is named serial. This method searches
|
|
all lookup variants to find the value.
|
|
|
|
Returns:
|
|
Just the value string for form validation. The modifier is reconstructed
|
|
during rendering from the query parameter names.
|
|
"""
|
|
# Special handling for empty - check if field__empty exists
|
|
empty_param = f"{name}__empty"
|
|
if empty_param in data:
|
|
# Return the boolean value for empty lookup
|
|
return data.get(empty_param)
|
|
|
|
# Try exact field name first
|
|
value = self.original_widget.value_from_datadict(data, files, name)
|
|
|
|
# If not found, check all modifier variants
|
|
# Note: SelectMultiple returns [] (empty list) when not found, not None
|
|
if value is None or (isinstance(value, list) and len(value) == 0):
|
|
for lookup, _ in self.lookups:
|
|
if lookup == 'exact':
|
|
continue # Already checked above
|
|
# Skip empty_true/false variants - they're handled above
|
|
if lookup in (MODIFIER_EMPTY_TRUE, MODIFIER_EMPTY_FALSE):
|
|
continue
|
|
lookup_name = f"{name}__{lookup}"
|
|
test_value = self.original_widget.value_from_datadict(data, files, lookup_name)
|
|
if test_value is not None:
|
|
value = test_value
|
|
break
|
|
|
|
# Return None if no value found (prevents field appearing in changed_data)
|
|
# Handle all widget empty value representations
|
|
if value is None:
|
|
return None
|
|
if isinstance(value, str) and not value.strip():
|
|
return None
|
|
if isinstance(value, (list, tuple)) and len(value) == 0:
|
|
return None
|
|
|
|
# Return just the value for form validation
|
|
return value
|
|
|
|
def get_context(self, name, value, attrs):
|
|
"""
|
|
Build context for template rendering.
|
|
|
|
Includes both the original widget's context and our modifier-specific data.
|
|
Note: value is now just a simple value (string/int/etc), not a dict.
|
|
The JavaScript initializeFromURL() will set the correct modifier dropdown
|
|
value based on URL parameters.
|
|
"""
|
|
# Propagate any attrs set on the wrapper (like data-url from get_bound_field)
|
|
# to the original widget before rendering
|
|
self.original_widget.attrs.update(self.attrs)
|
|
|
|
# Get context from the original widget
|
|
original_context = self.original_widget.get_context(name, value, attrs)
|
|
|
|
# Build our wrapper context
|
|
context = super().get_context(name, value, attrs)
|
|
context['widget']['original_widget'] = original_context['widget']
|
|
context['widget']['lookups'] = self.lookups
|
|
context['widget']['field_name'] = name
|
|
|
|
# Default to 'exact' - JavaScript will update based on URL params
|
|
context['widget']['current_modifier'] = 'exact'
|
|
context['widget']['current_value'] = value or ''
|
|
|
|
# Translatable placeholder for empty lookups
|
|
context['widget']['empty_placeholder'] = _('(automatically set)')
|
|
|
|
return context
|