From 6d365b8716a244796023c1e080c0a687431426e7 Mon Sep 17 00:00:00 2001 From: Piotr Dobrowolski Date: Sun, 8 Oct 2017 22:39:23 +0200 Subject: [PATCH] Render paths in parent autocomplete widget --- storage/admin.py | 7 ++++++ .../admin/storage/item/change_form.html | 22 +++++++++++++++++++ storage/urls.py | 3 ++- storage/views.py | 20 +++++++++++++++++ 4 files changed, 51 insertions(+), 1 deletion(-) diff --git a/storage/admin.py b/storage/admin.py index 034bb1c..84014c3 100644 --- a/storage/admin.py +++ b/storage/admin.py @@ -10,6 +10,13 @@ class ItemSelectWidget(ModelSelect2Widget): 'description__icontains' ] + def __init__(self, *args, **kwargs): + kwargs['data_view'] = 'item-complete' + super(ItemSelectWidget, self).__init__(*args, **kwargs) + + def label_from_instance(self, obj): + return obj.name + class ItemForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput()) diff --git a/storage/templates/admin/storage/item/change_form.html b/storage/templates/admin/storage/item/change_form.html index aa7dff0..ea0e6ad 100644 --- a/storage/templates/admin/storage/item/change_form.html +++ b/storage/templates/admin/storage/item/change_form.html @@ -11,3 +11,25 @@ {{ block.super }} {% endblock %} + +{% block content %}{{ block.super }} + +{% endblock %} diff --git a/storage/urls.py b/storage/urls.py index 4d861b3..d9f9582 100644 --- a/storage/urls.py +++ b/storage/urls.py @@ -1,9 +1,10 @@ from django.conf.urls import include, url -from storage.views import index, search, item_display, label_lookup +from storage.views import index, search, item_display, label_lookup, ItemSelectView urlpatterns = [ url(r'^$', index), url(r'^search$', search), url(r'^item/(?P.*)$', item_display, name='item-display'), + url(r'^autocomplete.json$', ItemSelectView.as_view(), name='item-complete'), url(r'^(?P[^/]*)$', label_lookup, name='label-lookup'), ] diff --git a/storage/views.py b/storage/views.py index acc6ffd..4d6088e 100644 --- a/storage/views.py +++ b/storage/views.py @@ -1,6 +1,8 @@ from django.shortcuts import render, get_object_or_404, redirect from storage.models import Item, Label from django.contrib.postgres.search import SearchVector +from django_select2.views import AutoResponseView +from django.http import Http404, JsonResponse import shlex def apply_smart_search(query, objects): @@ -69,3 +71,21 @@ def item_display(request, pk): def label_lookup(request, pk): label = get_object_or_404(Label, pk=pk) return redirect(label.item) + +class ItemSelectView(AutoResponseView): + def get(self, request, *args, **kwargs): + self.widget = self.get_widget_or_404() + self.term = kwargs.get('term', request.GET.get('term', '')) + self.object_list = self.get_queryset() + context = self.get_context_data() + return JsonResponse({ + 'results': [ + { + 'text': obj.name, + 'path': [o.name for o in obj.get_ancestors()], + 'id': obj.pk, + } + for obj in context['object_list'] + ], + 'more': context['page_obj'].has_next() + })