Last active
August 3, 2017 08:25
-
-
Save codingjoe/531d221272c4d080c695dd8309fc0b00 to your computer and use it in GitHub Desktop.
dependent fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/django_select2/forms.py b/django_select2/forms.py | |
index f013bcc..f760e18 100644 | |
--- a/django_select2/forms.py | |
+++ b/django_select2/forms.py | |
@@ -182,10 +182,15 @@ class HeavySelect2Mixin(object): | |
Args: | |
data_view (str): URL pattern name | |
data_url (str): URL | |
+ dependent_fields (List[str]): List of dependent parent fields. | |
+ The value of the dependent field will be passed as to :func:`.filter_queryset`. | |
+ It can be used to further restrict the search results. For example, a city | |
+ widget could be dependent on a country. | |
""" | |
self.data_view = kwargs.pop('data_view', None) | |
self.data_url = kwargs.pop('data_url', None) | |
+ self.dependent_fields = kwargs.pop('dependent_fields', []) | |
if not (self.data_view or self.data_url): | |
raise ValueError('You must ether specify "data_view" or "data_url".') | |
self.userGetValTextFuncName = kwargs.pop('userGetValTextFuncName', 'null') | |
@@ -209,6 +214,7 @@ class HeavySelect2Mixin(object): | |
attrs.setdefault('data-ajax--cache', "true") | |
attrs.setdefault('data-ajax--type', "GET") | |
attrs.setdefault('data-minimum-input-length', 2) | |
+ attrs.setdefault('data-select2-dependent-fields', " ".join(self.dependent_fields)) | |
attrs['class'] += ' django-select2-heavy' | |
return attrs | |
@@ -351,12 +357,13 @@ class ModelSelect2Mixin(object): | |
'url': self.get_url(), | |
}) | |
- def filter_queryset(self, term, queryset=None): | |
+ def filter_queryset(self, term, queryset=None, **kwargs): | |
""" | |
Return QuerySet filtered by search_fields matching the passed term. | |
Args: | |
term (str): Search term | |
+ **kwargs: Dependent fields and their values. | |
Returns: | |
QuerySet: Filtered QuerySet | |
diff --git a/django_select2/views.py b/django_select2/views.py | |
index 71a12aa..cc99a6f 100644 | |
--- a/django_select2/views.py | |
+++ b/django_select2/views.py | |
@@ -52,7 +52,11 @@ class AutoResponseView(BaseListView): | |
def get_queryset(self): | |
"""Get QuerySet from cached widget.""" | |
- return self.widget.filter_queryset(self.term, self.queryset) | |
+ kwargs = { | |
+ field: self.request.GET.get(field, '') | |
+ for field in self.widget.dependent_fields | |
+ } | |
+ return self.widget.filter_queryset(self.term, self.queryset, **kwargs) | |
def get_paginate_by(self, queryset): | |
"""Paginate response by size of widget's `max_results` parameter.""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment