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

Filter without saving #108

Open
wants to merge 18 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 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
80 changes: 71 additions & 9 deletions advanced_filters/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
from django.shortcuts import resolve_url
from django.utils.translation import ugettext_lazy as _

from .forms import AdvancedFilterForm
from .forms import AdvancedFilterForm, AdvancedFilterQueryForm
from .models import AdvancedFilter
from .q_serializer import QSerializer


logger = logging.getLogger('advanced_filters.admin')
Expand Down Expand Up @@ -43,6 +44,31 @@ def queryset(self, request, queryset):
return queryset


class AdvancedQueryFilters(admin.SimpleListFilter):
"""Allow filtering by advanced filters query"""
title = ' '
template = 'admin/query_filter.html'

parameter_name = '_aquery'

def lookups(self, request, model_admin):
return None

def queryset(self, request, queryset):
if self.value():
query_serializer = QSerializer(base64=True)
query = query_serializer.loads(self.value())
return queryset.filter(query).distinct()

return queryset

def choices(self, changelist):
return []

def has_output(self):
return True


class AdminAdvancedFiltersMixin(object):
""" Generic AdvancedFilters mixin """
advanced_change_list_template = "admin/advanced_filters.html"
Expand All @@ -56,15 +82,24 @@ def __init__(self, *args, **kwargs):
self.original_change_list_template = "admin/change_list.html"
self.change_list_template = self.advanced_change_list_template
# add list filters to filters
self.list_filter = (AdvancedListFilters,) + tuple(self.list_filter)

def save_advanced_filter(self, request, form):
self.list_filter = (AdvancedListFilters, AdvancedQueryFilters,) + tuple(self.list_filter)

def save_advanced_filter(self, request, form, save_instance):
if '_just_filter' in request.POST:
search_query = form.generate_query()
query_serializer = QSerializer(base64=True)
b64_query = query_serializer.dumps(search_query)
url = "{path}?_aquery={query}"\
.format(path=request.path, query=b64_query)
return HttpResponseRedirect(url)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about we add this into it's own method filter_without_saving or filter_ad_hoc or some other name, and allow it to be called from adv_filters_handle if not saving.

if form.is_valid():
afilter = form.save(commit=False)
afilter.created_by = request.user
afilter.query = form.generate_query()
afilter.save()
afilter.users.add(request.user)

if save_instance:
afilter.save()
afilter.users.add(request.user)
messages.add_message(
request, messages.SUCCESS,
_('Advanced filter added successfully.')
Expand All @@ -77,9 +112,36 @@ def save_advanced_filter(self, request, form):
elif request.method == "POST":
logger.info('Failed saving advanced filter, params: %s', form.data)

def get_advanced_filter_data(self, request):
if request.POST.get('action') == 'advanced_filters':
return request.POST, True

search_query = request.GET.get('_aquery')
if search_query:
query_serializer = QSerializer(base64=True)
raw_query = query_serializer.loads(search_query, raw=True)
query_list = query_serializer.get_field_values_list(raw_query)

data = {
'form-TOTAL_FORMS': 0,
'form-INITIAL_FORMS': 0,
'title': 'unsaved filter'
}

for idx, query in enumerate(query_list):
query_dict = AdvancedFilterQueryForm._parse_query_dict(query, self.model)

for key, value in query_dict.items():
data['form-{idx}-{key}'.format(idx=idx, key=key)] = value

data['form-TOTAL_FORMS'] += 1

return data, False
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The above means to initialize the forms when querying without saving? If so, perhaps we can use AdvancedFilterForm.initialize_form to make this more cleaner? Or is it impossible?


return None, False

def adv_filters_handle(self, request, extra_context={}):
data = request.POST if request.POST.get(
'action') == 'advanced_filters' else None
data, save_instance = self.get_advanced_filter_data(request)
adv_filters_form = self.advanced_filter_form(
data=data, model_admin=self, extra_form=True)
extra_context.update({
Expand All @@ -88,7 +150,7 @@ def adv_filters_handle(self, request, extra_context={}):
'current_afilter': request.GET.get('_afilter'),
'app_label': self.opts.app_label,
})
return self.save_advanced_filter(request, adv_filters_form)
return self.save_advanced_filter(request, adv_filters_form, save_instance)

def changelist_view(self, request, extra_context=None):
"""Add advanced_filters form to changelist context"""
Expand Down
1 change: 1 addition & 0 deletions advanced_filters/templates/admin/advanced_filters.html
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ <h1>{% trans "Create advanced filter" %}:</h1>
<br />
<input method="POST" type="submit" value="{% trans "Save" %}">
<input method="POST" name="_save_goto" type="submit" value="{% trans "Save & Filter Now!" %}">
<input method="POST" name="_just_filter" type="submit" value="{% trans "Filter" %}">
<a href="#" class="grp-button" style="margin:auto" onclick="$.magnificPopup.close();">{% trans "Cancel" %}</a>
</form>

Expand Down
1 change: 1 addition & 0 deletions advanced_filters/templates/admin/query_filter.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{# for now - make filter hidden in sidebar #}