django-searchkit 1.0__py3-none-any.whl → 1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- build/lib/build/lib/build/lib/example/example/__init__.py +0 -0
- build/lib/build/lib/build/lib/example/example/admin.py +16 -0
- build/lib/build/lib/build/lib/example/example/asgi.py +16 -0
- build/lib/build/lib/build/lib/example/example/management/__init__.py +0 -0
- build/lib/build/lib/build/lib/example/example/management/commands/__init__.py +0 -0
- build/lib/build/lib/build/lib/example/example/management/commands/createtestdata.py +62 -0
- build/lib/build/lib/build/lib/example/example/migrations/0001_initial.py +48 -0
- build/lib/build/lib/build/lib/example/example/migrations/__init__.py +0 -0
- build/lib/build/lib/build/lib/example/example/models.py +38 -0
- build/lib/build/lib/build/lib/example/example/settings.py +125 -0
- build/lib/build/lib/build/lib/example/example/urls.py +23 -0
- build/lib/build/lib/build/lib/example/example/wsgi.py +16 -0
- build/lib/build/lib/build/lib/searchkit/__init__.py +0 -0
- build/lib/build/lib/build/lib/searchkit/__version__.py +16 -0
- build/lib/build/lib/build/lib/searchkit/admin.py +30 -0
- build/lib/build/lib/build/lib/searchkit/apps.py +6 -0
- build/lib/build/lib/build/lib/searchkit/filters.py +28 -0
- build/lib/build/lib/build/lib/searchkit/forms/__init__.py +5 -0
- build/lib/build/lib/build/lib/searchkit/forms/fields.py +55 -0
- build/lib/build/lib/build/lib/searchkit/forms/search.py +62 -0
- build/lib/build/lib/build/lib/searchkit/forms/searchkit.py +154 -0
- build/lib/build/lib/build/lib/searchkit/forms/utils.py +178 -0
- build/lib/build/lib/build/lib/searchkit/migrations/0001_initial.py +30 -0
- build/lib/build/lib/build/lib/searchkit/migrations/0002_rename_searchkitsearch_search.py +18 -0
- build/lib/build/lib/build/lib/searchkit/migrations/__init__.py +0 -0
- build/lib/build/lib/build/lib/searchkit/models.py +21 -0
- build/lib/build/lib/build/lib/searchkit/templatetags/__init__.py +0 -0
- build/lib/build/lib/build/lib/searchkit/templatetags/searchkit.py +20 -0
- build/lib/build/lib/build/lib/searchkit/tests.py +400 -0
- build/lib/build/lib/build/lib/searchkit/urls.py +7 -0
- build/lib/build/lib/build/lib/searchkit/views.py +23 -0
- build/lib/build/lib/example/example/__init__.py +0 -0
- build/lib/build/lib/example/example/admin.py +16 -0
- build/lib/build/lib/example/example/asgi.py +16 -0
- build/lib/build/lib/example/example/management/__init__.py +0 -0
- build/lib/build/lib/example/example/management/commands/__init__.py +0 -0
- build/lib/build/lib/example/example/management/commands/createtestdata.py +62 -0
- build/lib/build/lib/example/example/migrations/0001_initial.py +48 -0
- build/lib/build/lib/example/example/migrations/__init__.py +0 -0
- build/lib/build/lib/example/example/models.py +38 -0
- build/lib/build/lib/example/example/settings.py +125 -0
- build/lib/build/lib/example/example/urls.py +23 -0
- build/lib/build/lib/example/example/wsgi.py +16 -0
- build/lib/build/lib/searchkit/__init__.py +0 -0
- build/lib/build/lib/searchkit/__version__.py +16 -0
- build/lib/build/lib/searchkit/admin.py +30 -0
- build/lib/build/lib/searchkit/apps.py +6 -0
- build/lib/build/lib/searchkit/filters.py +28 -0
- build/lib/build/lib/searchkit/forms/__init__.py +5 -0
- build/lib/build/lib/searchkit/forms/fields.py +55 -0
- build/lib/build/lib/searchkit/forms/search.py +62 -0
- build/lib/build/lib/searchkit/forms/searchkit.py +154 -0
- build/lib/build/lib/searchkit/forms/utils.py +178 -0
- build/lib/build/lib/searchkit/migrations/0001_initial.py +30 -0
- build/lib/build/lib/searchkit/migrations/0002_rename_searchkitsearch_search.py +18 -0
- build/lib/build/lib/searchkit/migrations/__init__.py +0 -0
- build/lib/build/lib/searchkit/models.py +21 -0
- build/lib/build/lib/searchkit/templatetags/__init__.py +0 -0
- build/lib/build/lib/searchkit/templatetags/searchkit.py +20 -0
- build/lib/build/lib/searchkit/tests.py +400 -0
- build/lib/build/lib/searchkit/urls.py +7 -0
- build/lib/build/lib/searchkit/views.py +23 -0
- build/lib/example/example/admin.py +1 -1
- build/lib/searchkit/__version__.py +1 -1
- build/lib/searchkit/admin.py +4 -4
- build/lib/searchkit/filters.py +10 -13
- build/lib/searchkit/forms/__init__.py +5 -3
- build/lib/searchkit/forms/search.py +37 -17
- build/lib/searchkit/forms/searchkit.py +60 -95
- build/lib/searchkit/forms/utils.py +44 -15
- build/lib/searchkit/migrations/0002_rename_searchkitsearch_search.py +18 -0
- build/lib/searchkit/models.py +2 -4
- build/lib/searchkit/templatetags/searchkit.py +0 -27
- build/lib/searchkit/tests.py +200 -50
- build/lib/searchkit/urls.py +1 -2
- build/lib/searchkit/views.py +11 -18
- {django_searchkit-1.0.dist-info → django_searchkit-1.2.dist-info}/METADATA +9 -24
- django_searchkit-1.2.dist-info/RECORD +130 -0
- example/example/admin.py +1 -1
- searchkit/__version__.py +1 -1
- searchkit/admin.py +4 -4
- searchkit/filters.py +10 -13
- searchkit/forms/__init__.py +5 -3
- searchkit/forms/search.py +37 -17
- searchkit/forms/searchkit.py +60 -95
- searchkit/forms/utils.py +44 -15
- searchkit/migrations/0002_rename_searchkitsearch_search.py +18 -0
- searchkit/models.py +2 -4
- searchkit/templatetags/searchkit.py +0 -27
- searchkit/tests.py +200 -50
- searchkit/urls.py +1 -2
- searchkit/views.py +11 -18
- django_searchkit-1.0.dist-info/RECORD +0 -66
- {django_searchkit-1.0.dist-info → django_searchkit-1.2.dist-info}/WHEEL +0 -0
- {django_searchkit-1.0.dist-info → django_searchkit-1.2.dist-info}/licenses/LICENCE +0 -0
- {django_searchkit-1.0.dist-info → django_searchkit-1.2.dist-info}/top_level.txt +0 -0
- {django_searchkit-1.0.dist-info → django_searchkit-1.2.dist-info}/zip-safe +0 -0
@@ -0,0 +1,125 @@
|
|
1
|
+
"""
|
2
|
+
Django settings for example project.
|
3
|
+
|
4
|
+
Generated by 'django-admin startproject' using Django 4.1.6.
|
5
|
+
|
6
|
+
For more information on this file, see
|
7
|
+
https://docs.djangoproject.com/en/4.1/topics/settings/
|
8
|
+
|
9
|
+
For the full list of settings and their values, see
|
10
|
+
https://docs.djangoproject.com/en/4.1/ref/settings/
|
11
|
+
"""
|
12
|
+
|
13
|
+
from pathlib import Path
|
14
|
+
|
15
|
+
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
16
|
+
BASE_DIR = Path(__file__).resolve().parent.parent
|
17
|
+
|
18
|
+
|
19
|
+
# Quick-start development settings - unsuitable for production
|
20
|
+
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
|
21
|
+
|
22
|
+
# SECURITY WARNING: keep the secret key used in production secret!
|
23
|
+
SECRET_KEY = 'django-insecure-^@et7v8l)mu@#@tooytj77v&jtkqy&i^wgp9+ro&v!rb6f1y__'
|
24
|
+
|
25
|
+
# SECURITY WARNING: don't run with debug turned on in production!
|
26
|
+
DEBUG = True
|
27
|
+
|
28
|
+
ALLOWED_HOSTS = []
|
29
|
+
|
30
|
+
|
31
|
+
# Application definition
|
32
|
+
|
33
|
+
INSTALLED_APPS = [
|
34
|
+
'example',
|
35
|
+
'searchkit',
|
36
|
+
'django.contrib.admin',
|
37
|
+
'django.contrib.auth',
|
38
|
+
'django.contrib.contenttypes',
|
39
|
+
'django.contrib.sessions',
|
40
|
+
'django.contrib.messages',
|
41
|
+
'django.contrib.staticfiles',
|
42
|
+
]
|
43
|
+
|
44
|
+
MIDDLEWARE = [
|
45
|
+
'django.middleware.security.SecurityMiddleware',
|
46
|
+
'django.contrib.sessions.middleware.SessionMiddleware',
|
47
|
+
'django.middleware.common.CommonMiddleware',
|
48
|
+
'django.middleware.csrf.CsrfViewMiddleware',
|
49
|
+
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
50
|
+
'django.contrib.messages.middleware.MessageMiddleware',
|
51
|
+
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
52
|
+
]
|
53
|
+
|
54
|
+
ROOT_URLCONF = 'example.urls'
|
55
|
+
|
56
|
+
TEMPLATES = [
|
57
|
+
{
|
58
|
+
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
59
|
+
'DIRS': [],
|
60
|
+
'APP_DIRS': True,
|
61
|
+
'OPTIONS': {
|
62
|
+
'context_processors': [
|
63
|
+
'django.template.context_processors.debug',
|
64
|
+
'django.template.context_processors.request',
|
65
|
+
'django.contrib.auth.context_processors.auth',
|
66
|
+
'django.contrib.messages.context_processors.messages',
|
67
|
+
],
|
68
|
+
},
|
69
|
+
},
|
70
|
+
]
|
71
|
+
|
72
|
+
WSGI_APPLICATION = 'example.wsgi.application'
|
73
|
+
|
74
|
+
|
75
|
+
# Database
|
76
|
+
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
|
77
|
+
|
78
|
+
DATABASES = {
|
79
|
+
'default': {
|
80
|
+
'ENGINE': 'django.db.backends.sqlite3',
|
81
|
+
'NAME': BASE_DIR / 'db.sqlite3',
|
82
|
+
}
|
83
|
+
}
|
84
|
+
|
85
|
+
|
86
|
+
# Password validation
|
87
|
+
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
|
88
|
+
|
89
|
+
AUTH_PASSWORD_VALIDATORS = [
|
90
|
+
{
|
91
|
+
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
92
|
+
},
|
93
|
+
{
|
94
|
+
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
95
|
+
},
|
96
|
+
{
|
97
|
+
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
98
|
+
},
|
99
|
+
{
|
100
|
+
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
101
|
+
},
|
102
|
+
]
|
103
|
+
|
104
|
+
|
105
|
+
# Internationalization
|
106
|
+
# https://docs.djangoproject.com/en/4.1/topics/i18n/
|
107
|
+
|
108
|
+
LANGUAGE_CODE = 'en-us'
|
109
|
+
|
110
|
+
TIME_ZONE = 'UTC'
|
111
|
+
|
112
|
+
USE_I18N = True
|
113
|
+
|
114
|
+
USE_TZ = True
|
115
|
+
|
116
|
+
|
117
|
+
# Static files (CSS, JavaScript, Images)
|
118
|
+
# https://docs.djangoproject.com/en/4.1/howto/static-files/
|
119
|
+
|
120
|
+
STATIC_URL = 'static/'
|
121
|
+
|
122
|
+
# Default primary key field type
|
123
|
+
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
|
124
|
+
|
125
|
+
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
@@ -0,0 +1,23 @@
|
|
1
|
+
"""example URL Configuration
|
2
|
+
|
3
|
+
The `urlpatterns` list routes URLs to views. For more information please see:
|
4
|
+
https://docs.djangoproject.com/en/4.1/topics/http/urls/
|
5
|
+
Examples:
|
6
|
+
Function views
|
7
|
+
1. Add an import: from my_app import views
|
8
|
+
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
9
|
+
Class-based views
|
10
|
+
1. Add an import: from other_app.views import Home
|
11
|
+
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
12
|
+
Including another URLconf
|
13
|
+
1. Import the include() function: from django.urls import include, path
|
14
|
+
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
15
|
+
"""
|
16
|
+
from django.contrib import admin
|
17
|
+
from django.urls import path, include
|
18
|
+
|
19
|
+
|
20
|
+
urlpatterns = [
|
21
|
+
path('', include('searchkit.urls')),
|
22
|
+
path('admin/', admin.site.urls),
|
23
|
+
]
|
@@ -0,0 +1,16 @@
|
|
1
|
+
"""
|
2
|
+
WSGI config for example project.
|
3
|
+
|
4
|
+
It exposes the WSGI callable as a module-level variable named ``application``.
|
5
|
+
|
6
|
+
For more information on this file, see
|
7
|
+
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/
|
8
|
+
"""
|
9
|
+
|
10
|
+
import os
|
11
|
+
|
12
|
+
from django.core.wsgi import get_wsgi_application
|
13
|
+
|
14
|
+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'example.settings')
|
15
|
+
|
16
|
+
application = get_wsgi_application()
|
File without changes
|
@@ -0,0 +1,16 @@
|
|
1
|
+
"""
|
2
|
+
This project uses the Semantic Versioning scheme in conjunction with PEP 0440:
|
3
|
+
<http://semver.org/>
|
4
|
+
<https://www.python.org/dev/peps/pep-0440>
|
5
|
+
|
6
|
+
Major versions introduce significant changes to the API, and backwards
|
7
|
+
compatibility is not guaranteed. Minor versions are for new features and other
|
8
|
+
backwards-compatible changes to the API. Patch versions are for bug fixes and
|
9
|
+
internal code changes that do not affect the API. Development versions are
|
10
|
+
incomplete states of a release .
|
11
|
+
|
12
|
+
Version 0.x should be considered a development version with an unstable API,
|
13
|
+
and backwards compatibility is not guaranteed for minor versions.
|
14
|
+
"""
|
15
|
+
|
16
|
+
__version__ = "1.2"
|
@@ -0,0 +1,30 @@
|
|
1
|
+
from django.contrib import admin
|
2
|
+
from django.http import HttpResponseRedirect
|
3
|
+
from django.urls import reverse
|
4
|
+
from .models import Search
|
5
|
+
from .forms import SearchForm
|
6
|
+
from .filters import SearchkitFilter
|
7
|
+
|
8
|
+
|
9
|
+
@admin.register(Search)
|
10
|
+
class SearchkitSearchAdmin(admin.ModelAdmin):
|
11
|
+
form = SearchForm
|
12
|
+
list_display = ('name', 'contenttype', 'created_date')
|
13
|
+
|
14
|
+
def get_url_for_applied_search(self, obj):
|
15
|
+
app_label = obj.contenttype.app_label
|
16
|
+
model_name = obj.contenttype.model
|
17
|
+
base_url = reverse(f'admin:{app_label}_{model_name}_changelist')
|
18
|
+
return f'{base_url}?{SearchkitFilter.parameter_name}={obj.pk}'
|
19
|
+
|
20
|
+
def response_add(self, request, obj, *args, **kwargs):
|
21
|
+
if '_save_and_apply' in request.POST:
|
22
|
+
return HttpResponseRedirect(self.get_url_for_applied_search(obj))
|
23
|
+
else:
|
24
|
+
return super().response_add(request, obj, *args, **kwargs)
|
25
|
+
|
26
|
+
def response_change(self, request, obj, *args, **kwargs):
|
27
|
+
if '_save_and_apply' in request.POST:
|
28
|
+
return HttpResponseRedirect(self.get_url_for_applied_search(obj))
|
29
|
+
else:
|
30
|
+
return super().response_change(request, obj, *args, **kwargs)
|
@@ -0,0 +1,28 @@
|
|
1
|
+
from django.contrib.admin import SimpleListFilter
|
2
|
+
from django.contrib.contenttypes.models import ContentType
|
3
|
+
from .models import Search
|
4
|
+
|
5
|
+
|
6
|
+
class SearchkitFilter(SimpleListFilter):
|
7
|
+
title = 'Searchkit Filter'
|
8
|
+
parameter_name = 'search'
|
9
|
+
template = 'searchkit/searchkit_filter.html'
|
10
|
+
|
11
|
+
def __init__(self, request, params, model, model_admin):
|
12
|
+
# We need the app_label and model as get parameter for the new search
|
13
|
+
# link.
|
14
|
+
self.searchkit_model = ContentType.objects.get_for_model(model)
|
15
|
+
super().__init__(request, params, model, model_admin)
|
16
|
+
|
17
|
+
def has_output(self):
|
18
|
+
return True
|
19
|
+
|
20
|
+
def lookups(self, request, model_admin):
|
21
|
+
searches = Search.objects.filter(contenttype=self.searchkit_model).order_by('-created_date')
|
22
|
+
return [(str(obj.id), obj.name) for obj in searches]
|
23
|
+
|
24
|
+
def queryset(self, request, queryset):
|
25
|
+
# Filter the queryset based on the selected SearchkitSearch object
|
26
|
+
if self.value():
|
27
|
+
search = Search.objects.get(id=int(self.value()))
|
28
|
+
return queryset.filter(**search.as_lookups())
|
@@ -0,0 +1,55 @@
|
|
1
|
+
from django import forms
|
2
|
+
from django.utils.translation import gettext_lazy as _
|
3
|
+
|
4
|
+
|
5
|
+
class RangeWidget(forms.MultiWidget):
|
6
|
+
def decompress(self, value):
|
7
|
+
"""The value should be already a list."""
|
8
|
+
if value:
|
9
|
+
return value
|
10
|
+
else:
|
11
|
+
return [None, None]
|
12
|
+
|
13
|
+
|
14
|
+
class BaseRangeField(forms.MultiValueField):
|
15
|
+
incomplete_message = None
|
16
|
+
field_type = None
|
17
|
+
widget_type = None
|
18
|
+
field_kwargs = dict()
|
19
|
+
|
20
|
+
def __init__(self, **kwargs):
|
21
|
+
error_messages = dict(incomplete=self.incomplete_message)
|
22
|
+
widget = RangeWidget(widgets=[self.widget_type, self.widget_type])
|
23
|
+
fields = (
|
24
|
+
self.field_type(label=_('From'), **self.field_kwargs),
|
25
|
+
self.field_type(label=_('To'), **self.field_kwargs),
|
26
|
+
)
|
27
|
+
super().__init__(
|
28
|
+
fields=fields,
|
29
|
+
widget=widget,
|
30
|
+
error_messages=error_messages,
|
31
|
+
require_all_fields=True,
|
32
|
+
**kwargs
|
33
|
+
)
|
34
|
+
|
35
|
+
def compress(self, data_list):
|
36
|
+
"""We want the data list as data list."""
|
37
|
+
return data_list
|
38
|
+
|
39
|
+
|
40
|
+
class IntegerRangeField(BaseRangeField):
|
41
|
+
incomplete_message = _("Enter the first and the last number.")
|
42
|
+
field_type = forms.IntegerField
|
43
|
+
widget_type = forms.NumberInput
|
44
|
+
|
45
|
+
|
46
|
+
class DateRangeField(BaseRangeField):
|
47
|
+
incomplete_message = _("Enter the first and the last date.")
|
48
|
+
field_type = forms.DateField
|
49
|
+
widget_type = forms.DateInput
|
50
|
+
|
51
|
+
|
52
|
+
class DateTimeRangeField(BaseRangeField):
|
53
|
+
incomplete_message = _("Enter the first and the last datetime.")
|
54
|
+
field_type = forms.DateTimeField
|
55
|
+
widget_type = forms.DateTimeInput
|
@@ -0,0 +1,62 @@
|
|
1
|
+
from django import forms
|
2
|
+
from django.utils.functional import cached_property
|
3
|
+
from django.contrib.contenttypes.models import ContentType
|
4
|
+
from ..models import Search
|
5
|
+
from .searchkit import SearchkitModelForm
|
6
|
+
from .searchkit import searchkit_formset_factory
|
7
|
+
from .utils import MediaMixin
|
8
|
+
|
9
|
+
|
10
|
+
class SearchForm(MediaMixin, forms.ModelForm):
|
11
|
+
"""
|
12
|
+
Represents a SearchkitSearch model. Using a SearchkitFormSet for the data
|
13
|
+
json field.
|
14
|
+
"""
|
15
|
+
class Meta:
|
16
|
+
model = Search
|
17
|
+
fields = ['name']
|
18
|
+
|
19
|
+
@cached_property
|
20
|
+
def searchkit_model(self):
|
21
|
+
if self.instance.pk:
|
22
|
+
return self.instance.contenttype.model_class()
|
23
|
+
elif self.searchkit_model_form.is_valid():
|
24
|
+
return self.searchkit_model_form.cleaned_data['searchkit_model'].model_class()
|
25
|
+
elif 'searchkit_model' in self.searchkit_model_form.initial:
|
26
|
+
value = self.searchkit_model_form.initial['searchkit_model']
|
27
|
+
try:
|
28
|
+
return self.searchkit_model_form.fields['searchkit_model'].clean(value).model_class()
|
29
|
+
except forms.ValidationError:
|
30
|
+
return None
|
31
|
+
|
32
|
+
@cached_property
|
33
|
+
def searchkit_model_form(self):
|
34
|
+
kwargs = dict(data=self.data or None, initial=self.initial or None)
|
35
|
+
if self.instance.pk:
|
36
|
+
kwargs['initial'] = dict(searchkit_model=self.instance.contenttype)
|
37
|
+
return SearchkitModelForm(**kwargs)
|
38
|
+
|
39
|
+
@cached_property
|
40
|
+
def formset(self):
|
41
|
+
"""
|
42
|
+
A searchkit formset for the model.
|
43
|
+
"""
|
44
|
+
kwargs = dict()
|
45
|
+
if self.searchkit_model and self.data:
|
46
|
+
kwargs = dict(data=self.data)
|
47
|
+
elif self.searchkit_model and self.instance.pk:
|
48
|
+
kwargs = dict(initial=self.instance.data)
|
49
|
+
|
50
|
+
extra = 0 if self.instance.pk else 1
|
51
|
+
formset = searchkit_formset_factory(model=self.searchkit_model, extra=extra)
|
52
|
+
return formset(**kwargs)
|
53
|
+
|
54
|
+
def is_valid(self):
|
55
|
+
return self.formset.is_valid() and self.searchkit_model_form.is_valid and super().is_valid()
|
56
|
+
|
57
|
+
def clean(self):
|
58
|
+
if self.searchkit_model_form.is_valid():
|
59
|
+
self.instance.contenttype = self.searchkit_model_form.cleaned_data['searchkit_model']
|
60
|
+
if self.formset.is_valid():
|
61
|
+
self.instance.data = self.formset.cleaned_data
|
62
|
+
return super().clean()
|
@@ -0,0 +1,154 @@
|
|
1
|
+
from django import forms
|
2
|
+
from django.utils.translation import gettext_lazy as _
|
3
|
+
from django.utils.functional import cached_property
|
4
|
+
from .utils import CssClassMixin, FIELD_PLAN, OPERATOR_DESCRIPTION
|
5
|
+
from .utils import SUPPORTED_FIELDS
|
6
|
+
from .utils import ModelTree
|
7
|
+
from .utils import MediaMixin
|
8
|
+
from .utils import get_searchable_models
|
9
|
+
|
10
|
+
|
11
|
+
class SearchkitModelForm(forms.Form):
|
12
|
+
"""
|
13
|
+
Form to select a content type.
|
14
|
+
"""
|
15
|
+
searchkit_model = forms.ModelChoiceField(
|
16
|
+
queryset=get_searchable_models(),
|
17
|
+
label=_('Model'),
|
18
|
+
empty_label=_('Select a Model'),
|
19
|
+
widget=forms.Select(attrs={
|
20
|
+
"class": CssClassMixin.reload_on_change_css_class,
|
21
|
+
"data-total-forms": 1,
|
22
|
+
}),
|
23
|
+
)
|
24
|
+
|
25
|
+
|
26
|
+
class BaseSearchkitForm(MediaMixin, CssClassMixin, forms.Form):
|
27
|
+
"""
|
28
|
+
Searchkit form representing a model field lookup based on the field name,
|
29
|
+
the operator and one or two values.
|
30
|
+
|
31
|
+
The unbound form is composed of an index field (the count of the searchkit
|
32
|
+
form) and a choice field offering the names of the model fields.
|
33
|
+
|
34
|
+
The bound form is dynamically extended by the operator field or the operator and
|
35
|
+
the value field depending on the provided data
|
36
|
+
|
37
|
+
See the FIELD_PLAN variable for the logic of building the form.
|
38
|
+
"""
|
39
|
+
model = None # Set by the formset factory.
|
40
|
+
|
41
|
+
def __init__(self, *args, **kwargs):
|
42
|
+
super().__init__(*args, **kwargs)
|
43
|
+
self.model_tree = ModelTree(self.model)
|
44
|
+
self.model_field = None
|
45
|
+
self.field_plan = None
|
46
|
+
self.operator = None
|
47
|
+
self._add_field_name_field()
|
48
|
+
lookup = self._preload_clean_data('field')
|
49
|
+
self.model_field = self._get_model_field(lookup)
|
50
|
+
self.field_plan = next(iter([p for t, p in FIELD_PLAN.items() if t(self.model_field)]))
|
51
|
+
self._add_operator_field()
|
52
|
+
self.operator = self._preload_clean_data('operator')
|
53
|
+
self._add_value_field()
|
54
|
+
|
55
|
+
@cached_property
|
56
|
+
def unprefixed_data(self):
|
57
|
+
data = dict()
|
58
|
+
for key, value in self.data.items():
|
59
|
+
if key.startswith(self.prefix):
|
60
|
+
data[key[len(self.prefix) + 1:]] = value
|
61
|
+
return data
|
62
|
+
|
63
|
+
def _preload_clean_data(self, field_name):
|
64
|
+
# Try the initial value first since it is already cleaned.
|
65
|
+
if self.initial and field_name in self.initial:
|
66
|
+
return self.initial[field_name]
|
67
|
+
# Otherwise look up the data dict.
|
68
|
+
elif field_name in self.unprefixed_data:
|
69
|
+
try:
|
70
|
+
# Do we have a valid value?
|
71
|
+
return self.fields[field_name].clean(self.unprefixed_data[field_name])
|
72
|
+
except forms.ValidationError:
|
73
|
+
return self.fields[field_name].choices[0][0]
|
74
|
+
else:
|
75
|
+
# At last simply return the first option which will be the selected
|
76
|
+
# one.
|
77
|
+
return self.fields[field_name].choices[0][0]
|
78
|
+
|
79
|
+
def _get_model_field(self, lookup):
|
80
|
+
path = lookup.split('__')
|
81
|
+
field_name = path[-1]
|
82
|
+
if path[:-1]:
|
83
|
+
model = self.model_tree.get('__'.join(path[:-1])).model
|
84
|
+
else:
|
85
|
+
model = self.model
|
86
|
+
return model._meta.get_field(field_name)
|
87
|
+
|
88
|
+
def _get_model_field_choices(self):
|
89
|
+
choices = list()
|
90
|
+
label_path = list()
|
91
|
+
for node in self.model_tree.iterate():
|
92
|
+
label_path.append
|
93
|
+
for model_field in node.model._meta.fields:
|
94
|
+
if not any(isinstance(model_field, f) for f in SUPPORTED_FIELDS):
|
95
|
+
continue
|
96
|
+
if node.is_root:
|
97
|
+
lookup = model_field.name
|
98
|
+
label = f'`{model_field.verbose_name}`'
|
99
|
+
else:
|
100
|
+
lookup = f'{node.field_path}__{model_field.name}'
|
101
|
+
get_field_name = lambda f: getattr(f, 'verbose_name', f.name)
|
102
|
+
label_path = [f'`{get_field_name(n.field)}` => <{n.model._meta.verbose_name}>' for n in node.path[1:]]
|
103
|
+
label = ".".join(label_path + [f'`{model_field.verbose_name}`'])
|
104
|
+
choices.append((lookup, label))
|
105
|
+
return choices
|
106
|
+
|
107
|
+
def _add_field_name_field(self):
|
108
|
+
initial = self.initial.get('field')
|
109
|
+
choices = self._get_model_field_choices()
|
110
|
+
field = forms.ChoiceField(label=_('Model field'), choices=choices, initial=initial)
|
111
|
+
field.widget.attrs.update({"class": self.reload_on_change_css_class})
|
112
|
+
self.fields['field'] = field
|
113
|
+
|
114
|
+
def _add_operator_field(self):
|
115
|
+
initial = self.initial.get('operator')
|
116
|
+
choices = [(o, OPERATOR_DESCRIPTION[o]) for o in self.field_plan.keys()]
|
117
|
+
field = forms.ChoiceField(label=_('Operator'), choices=choices, initial=initial)
|
118
|
+
field.widget.attrs.update({"class": self.reload_on_change_css_class})
|
119
|
+
self.fields['operator'] = field
|
120
|
+
|
121
|
+
def _add_value_field(self):
|
122
|
+
initial = self.initial.get('value')
|
123
|
+
field_class = self.field_plan[self.operator][0]
|
124
|
+
if getattr(field_class, 'choices', None) and getattr(self.model_field, 'choices', None):
|
125
|
+
field = field_class(choices=self.model_field.choices, initial=initial)
|
126
|
+
else:
|
127
|
+
field = field_class()
|
128
|
+
self.fields['value'] = field
|
129
|
+
|
130
|
+
|
131
|
+
class BaseSearchkitFormSet(CssClassMixin, forms.BaseFormSet):
|
132
|
+
"""
|
133
|
+
Formset holding all searchkit forms.
|
134
|
+
"""
|
135
|
+
template_name = "searchkit/searchkit.html"
|
136
|
+
template_name_div = "searchkit/searchkit.html"
|
137
|
+
model = None # Set by the formset factory.
|
138
|
+
|
139
|
+
def add_prefix(self, index):
|
140
|
+
return "%s-%s-%s-%s" % (self.prefix, self.model._meta.app_label, self.model._meta.model_name, index)
|
141
|
+
|
142
|
+
@classmethod
|
143
|
+
def get_default_prefix(self):
|
144
|
+
return "searchkit"
|
145
|
+
|
146
|
+
|
147
|
+
def searchkit_formset_factory(model, **kwargs):
|
148
|
+
form = type('SearchkitForm', (BaseSearchkitForm,), dict(model=model))
|
149
|
+
formset = type('SearchkitFormSet', (BaseSearchkitFormSet,), dict(model=model))
|
150
|
+
return forms.formset_factory(
|
151
|
+
form=form,
|
152
|
+
formset=formset,
|
153
|
+
**kwargs
|
154
|
+
)
|