├── tests ├── tests │ ├── __init__.py │ ├── urls.py │ ├── wsgi.py │ └── settings.py ├── testapp │ ├── migrations │ │ ├── __init__.py │ │ ├── 0002_data.py │ │ └── 0001_initial.py │ ├── __init__.py │ ├── apps.py │ ├── views.py │ ├── models.py │ ├── tests.py │ ├── admin.py │ └── fixtures │ │ └── fixture.json └── static │ └── custom.css ├── requirements.txt ├── admin_auto_filters ├── __init__.py ├── apps.py ├── media │ ├── screenshot1.png │ └── screenshot2.png ├── static │ └── django-admin-autocomplete-filter │ │ ├── css │ │ └── autocomplete-fix.css │ │ └── js │ │ └── autocomplete_filter_qs.js ├── templates │ └── django-admin-autocomplete-filter │ │ └── autocomplete-filter.html ├── views.py └── filters.py ├── MANIFEST.in ├── tests_manage.py ├── setup.py ├── .gitignore ├── README.md └── LICENSE /tests/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django>=2.0 -------------------------------------------------------------------------------- /admin_auto_filters/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/testapp/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/static/custom.css: -------------------------------------------------------------------------------- 1 | /* custom css */ 2 | -------------------------------------------------------------------------------- /tests/testapp/__init__.py: -------------------------------------------------------------------------------- 1 | default_app_config = 'tests.testapp.apps.TestappConfig' 2 | -------------------------------------------------------------------------------- /admin_auto_filters/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class AdminAutoFiltersConfig(AppConfig): 5 | name = 'admin_auto_filters' 6 | -------------------------------------------------------------------------------- /admin_auto_filters/media/screenshot1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/farhan0581/django-admin-autocomplete-filter/HEAD/admin_auto_filters/media/screenshot1.png -------------------------------------------------------------------------------- /admin_auto_filters/media/screenshot2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/farhan0581/django-admin-autocomplete-filter/HEAD/admin_auto_filters/media/screenshot2.png -------------------------------------------------------------------------------- /admin_auto_filters/static/django-admin-autocomplete-filter/css/autocomplete-fix.css: -------------------------------------------------------------------------------- 1 | .select2-container { 2 | min-width: 16.5em; 3 | max-width: 100%; 4 | } -------------------------------------------------------------------------------- /tests/tests/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.urls import path 3 | 4 | urlpatterns = [ 5 | path('admin/', admin.site.urls), 6 | ] 7 | -------------------------------------------------------------------------------- /tests/testapp/apps.py: -------------------------------------------------------------------------------- 1 | """Defines the test app config.""" 2 | 3 | from django.apps import AppConfig 4 | 5 | 6 | class TestappConfig(AppConfig): 7 | name = 'tests.testapp' 8 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include LICENSE 3 | include requirements.txt 4 | recursive-include docs * 5 | recursive-include admin_auto_filters/static * 6 | recursive-include admin_auto_filters/templates * 7 | -------------------------------------------------------------------------------- /tests/tests/wsgi.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from django.core.wsgi import get_wsgi_application 4 | 5 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.tests.settings') 6 | 7 | application = get_wsgi_application() 8 | -------------------------------------------------------------------------------- /admin_auto_filters/templates/django-admin-autocomplete-filter/autocomplete-filter.html: -------------------------------------------------------------------------------- 1 | {% load i18n %} 2 | {% if not spec.is_placeholder_title %} 3 |

{% blocktrans with filter_title=title %} By {{ filter_title }} {% endblocktrans %}

4 | {% endif %} 5 | -------------------------------------------------------------------------------- /tests_manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | # To run tests, use `./tests_manage.py test tests` from base directory 8 | 9 | # To load (e.g.) the models, use `from tests.testapp.models import ...` 10 | 11 | 12 | def main(): 13 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.tests.settings') 14 | try: 15 | from django.core.management import execute_from_command_line 16 | except ImportError as exc: 17 | raise ImportError( 18 | "Couldn't import Django. Are you sure it's installed and " 19 | "available on your PYTHONPATH environment variable? Did you " 20 | "forget to activate a virtual environment?" 21 | ) from exc 22 | execute_from_command_line(sys.argv) 23 | 24 | 25 | if __name__ == '__main__': 26 | main() 27 | -------------------------------------------------------------------------------- /tests/testapp/migrations/0002_data.py: -------------------------------------------------------------------------------- 1 | """A data migration to load in fixtures.""" 2 | 3 | from django.core.management import call_command 4 | from django.db import migrations 5 | 6 | 7 | def load_fixture(apps, schema_editor): 8 | call_command('loaddata', 'fixture', app_label='testapp') 9 | 10 | 11 | def unload_fixture(apps, schema_editor): 12 | Book = apps.get_model("location", "Book") 13 | Collection = apps.get_model("location", "Collection") 14 | Food = apps.get_model("location", "Food") 15 | Person = apps.get_model("location", "Person") 16 | Book.objects.all().delete() 17 | Collection.objects.all().delete() 18 | Food.objects.all().delete() 19 | Person.objects.all().delete() 20 | 21 | 22 | class Migration(migrations.Migration): 23 | 24 | dependencies = [ 25 | ('testapp', '0001_initial'), 26 | ] 27 | 28 | operations = [ 29 | migrations.RunPython(load_fixture, reverse_code=unload_fixture), 30 | ] 31 | -------------------------------------------------------------------------------- /admin_auto_filters/views.py: -------------------------------------------------------------------------------- 1 | from django.http import JsonResponse 2 | from django.contrib.admin.views.autocomplete import AutocompleteJsonView as Base 3 | 4 | 5 | class AutocompleteJsonView(Base): 6 | """Overriding django admin's AutocompleteJsonView""" 7 | 8 | @staticmethod 9 | def display_text(obj): 10 | """ 11 | Hook to specify means for converting object to string for endpoint. 12 | """ 13 | return str(obj) 14 | 15 | def get(self, request, *args, **kwargs): 16 | self.term = request.GET.get('term', '') 17 | self.paginator_class = self.model_admin.paginator 18 | self.object_list = self.get_queryset() 19 | context = self.get_context_data() 20 | return JsonResponse({ 21 | 'results': [ 22 | {'id': str(obj.pk), 'text': self.display_text(obj)} 23 | for obj in context['object_list'] 24 | ], 25 | 'pagination': {'more': context['page_obj'].has_next()}, 26 | }) 27 | -------------------------------------------------------------------------------- /tests/testapp/views.py: -------------------------------------------------------------------------------- 1 | """Defines custom autocompletion views for the test app.""" 2 | 3 | from django.db.models import Q 4 | from admin_auto_filters.views import AutocompleteJsonView 5 | from .models import Food 6 | 7 | 8 | class FoodsThatAreFavorites(AutocompleteJsonView): 9 | """List only foods that are someone's favorite.""" 10 | 11 | @staticmethod 12 | def display_text(obj): 13 | return obj.alternate_name() 14 | 15 | def get_queryset(self): 16 | 17 | # Get items in use (would need to use related_query_name if applicable) 18 | foods = list(Food.objects.filter(person__isnull=False).values_list('id')) 19 | foods = list(set([item for sublist in foods for item in sublist if item is not None])) 20 | 21 | # Construct query 22 | qs = Food.objects.filter(id__in=foods).only('id', 'name') 23 | for bit in self.term.split(' '): 24 | qs = qs.filter(Q(id__icontains=bit) | Q(name__icontains=bit)) 25 | qs = qs.order_by('name') #.distinct() 26 | return qs 27 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import find_packages, setup 3 | 4 | with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: 5 | README = readme.read() 6 | 7 | setup( 8 | name='django-admin-autocomplete-filter', 9 | version='0.5', 10 | packages=find_packages(), 11 | include_package_data=True, 12 | description='A simple Django app to render list filters in django admin using autocomplete widget', 13 | long_description=README, 14 | long_description_content_type='text/markdown', 15 | url='https://github.com/farhan0581/django-admin-autocomplete-filter', 16 | author='Farhan Khan', 17 | author_email='farhan0581@gmail.com', 18 | install_requires=[ 19 | 'django>=2.0', 20 | ], 21 | classifiers=[ 22 | 'Framework :: Django', 23 | 'Framework :: Django :: 2.0', # replace "X.Y" as appropriate 24 | 'Intended Audience :: Developers', 25 | 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', 26 | 'Operating System :: OS Independent', 27 | 'Programming Language :: Python :: 3.5', 28 | 'Programming Language :: Python :: 3.6', 29 | 'Topic :: Internet :: WWW/HTTP', 30 | 'Topic :: Software Development :: Libraries :: Python Modules', 31 | ], 32 | ) 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # MacOS 107 | .DS_Store 108 | 109 | # Backup files 110 | *~ 111 | 112 | # PyCharm 113 | .idea 114 | -------------------------------------------------------------------------------- /tests/tests/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for tests project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.2.7. 5 | """ 6 | 7 | import os 8 | from django.core.management.utils import get_random_secret_key 9 | 10 | BASE_DIR = os.path.dirname( 11 | os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 12 | 13 | SECRET_KEY = get_random_secret_key() 14 | 15 | DEBUG = True 16 | 17 | ALLOWED_HOSTS = [] 18 | 19 | INSTALLED_APPS = [ 20 | 'django.contrib.admin', 21 | 'django.contrib.auth', 22 | 'django.contrib.contenttypes', 23 | 'django.contrib.sessions', 24 | 'django.contrib.messages', 25 | 'django.contrib.staticfiles', 26 | 'admin_auto_filters', 27 | 'tests.testapp', 28 | ] 29 | 30 | MIDDLEWARE = [ 31 | 'django.middleware.security.SecurityMiddleware', 32 | 'django.contrib.sessions.middleware.SessionMiddleware', 33 | 'django.middleware.common.CommonMiddleware', 34 | 'django.middleware.csrf.CsrfViewMiddleware', 35 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 36 | 'django.contrib.messages.middleware.MessageMiddleware', 37 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 38 | ] 39 | 40 | ROOT_URLCONF = 'tests.tests.urls' 41 | 42 | TEMPLATES = [ 43 | { 44 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 45 | 'DIRS': [], 46 | 'APP_DIRS': True, 47 | 'OPTIONS': { 48 | 'context_processors': [ 49 | 'django.template.context_processors.debug', 50 | 'django.template.context_processors.request', 51 | 'django.contrib.auth.context_processors.auth', 52 | 'django.contrib.messages.context_processors.messages', 53 | ], 54 | }, 55 | }, 56 | ] 57 | 58 | WSGI_APPLICATION = 'tests.tests.wsgi.application' 59 | 60 | DATABASES = { 61 | 'default': { 62 | 'ENGINE': 'django.db.backends.sqlite3', 63 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 64 | } 65 | } 66 | 67 | AUTH_PASSWORD_VALIDATORS = [] 68 | 69 | LANGUAGE_CODE = 'en-us' 70 | 71 | TIME_ZONE = 'UTC' 72 | 73 | USE_I18N = True 74 | 75 | USE_L10N = True 76 | 77 | USE_TZ = True 78 | 79 | STATIC_URL = '/static/' 80 | 81 | STATICFILES_DIRS = [ 82 | os.path.join(BASE_DIR, "tests", "static"), 83 | ] 84 | -------------------------------------------------------------------------------- /tests/testapp/models.py: -------------------------------------------------------------------------------- 1 | """Defines the models for the test app.""" 2 | 3 | from django.db import models 4 | 5 | 6 | class Food(models.Model): 7 | name = models.CharField(max_length=100) 8 | 9 | def __repr__(self): 10 | return 'Food#' + str(self.id) 11 | 12 | def __str__(self): 13 | return self.name 14 | 15 | def alternate_name(self): 16 | return str(self.name).upper() 17 | 18 | 19 | class Collection(models.Model): 20 | name = models.CharField(max_length=100) 21 | curators = models.ManyToManyField('Person', blank=True) 22 | 23 | def __repr__(self): 24 | return 'Collection#' + str(self.id) 25 | 26 | def __str__(self): 27 | return self.name 28 | 29 | 30 | class Person(models.Model): 31 | name = models.CharField(max_length=100) 32 | best_friend = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) # may not be reciprocated 33 | twin = models.OneToOneField('self', on_delete=models.CASCADE, blank=True, null=True, related_name='rev_twin') 34 | siblings = models.ManyToManyField('self', blank=True) 35 | favorite_food = models.ForeignKey(Food, on_delete=models.CASCADE, blank=True, null=True) 36 | least_favorite_food = models.ForeignKey(Food, on_delete=models.CASCADE, blank=True, null=True, 37 | related_name='food_is_least_fav', related_query_name='people_with_this_least_fav_food') 38 | curated_collections = models.ManyToManyField(Collection, blank=True, db_table=Collection.curators.field.db_table) 39 | favorite_book = models.ForeignKey('Book', on_delete=models.CASCADE, blank=True, null=True, related_name='people_with_this_fav_book') 40 | 41 | def __repr__(self): 42 | return 'Person#' + str(self.id) 43 | 44 | def __str__(self): 45 | return self.name 46 | 47 | 48 | # Use this and curated_collections.db_table to set up reverse M2M 49 | # See https://code.djangoproject.com/ticket/897 50 | Person.curated_collections.through._meta.managed = False 51 | 52 | 53 | class Book(models.Model): 54 | isbn = models.IntegerField(primary_key=True) 55 | title = models.CharField(max_length=100) 56 | author = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True) 57 | coll = models.ForeignKey(Collection, on_delete=models.CASCADE, blank=True, null=True) # just for test purposes 58 | 59 | def __repr__(self): 60 | return 'Book#' + str(self.isbn) 61 | 62 | def __str__(self): 63 | return self.title 64 | -------------------------------------------------------------------------------- /admin_auto_filters/static/django-admin-autocomplete-filter/js/autocomplete_filter_qs.js: -------------------------------------------------------------------------------- 1 | django.jQuery(document).ready(function () { 2 | django.jQuery('#changelist-filter select, #grp-filters select').on( 3 | 'change', 4 | function (e, choice) { 5 | var val = django.jQuery(e.target).val() || ''; 6 | var class_name = this.className; 7 | var param = this.name; 8 | if (class_name.includes('admin-autocomplete')) 9 | { 10 | window.location.search = search_replace(param, val); 11 | } 12 | }); 13 | }); 14 | 15 | function search_replace(name, value) { 16 | var new_search_hash = search_to_hash(); 17 | if (value) { 18 | new_search_hash[decodeURIComponent(name)] = []; 19 | new_search_hash[decodeURIComponent(name)].push(decodeURIComponent(value)); 20 | } else { 21 | delete new_search_hash[decodeURIComponent(name)]; 22 | } 23 | return hash_to_search(new_search_hash); 24 | } 25 | 26 | function search_add(name, value) { 27 | var new_search_hash = search_to_hash(); 28 | if ( ! (decodeURIComponent(name) in new_search_hash)) { 29 | new_search_hash[decodeURIComponent(name)] = []; 30 | } 31 | new_search_hash[decodeURIComponent(name)].push(decodeURIComponent(value)); 32 | return hash_to_search(new_search_hash); 33 | } 34 | // pduey: remove a variable/value pair from the current query string and return updated href 35 | function search_remove(name, value) { 36 | var new_search_hash = search_to_hash(); 37 | if (new_search_hash[name].indexOf(value) >= 0) { 38 | new_search_hash[name].splice(new_search_hash[name].indexOf(value), 1); 39 | if (new_search_hash[name].length == 0) { 40 | delete new_search_hash[name]; 41 | } 42 | } 43 | return hash_to_search(new_search_hash); 44 | } 45 | 46 | function search_to_hash() { 47 | var h={}; 48 | if (window.location.search == undefined || window.location.search.length < 1) { return h;} 49 | q = window.location.search.slice(1).split('&'); 50 | for (var i = 0; i < q.length; i++) { 51 | var key_val = q[i].split('='); 52 | // replace '+' (alt space) char explicitly since decode does not 53 | var hkey = decodeURIComponent(key_val[0]).replace(/\+/g,' '); 54 | var hval = decodeURIComponent(key_val[1]).replace(/\+/g,' '); 55 | if (h[hkey] == undefined) { 56 | h[hkey] = []; 57 | } 58 | h[hkey].push(hval); 59 | } 60 | return h; 61 | } 62 | 63 | function hash_to_search(h) { 64 | var search = String("?"); 65 | for (var k in h) { 66 | if (k === '') { continue; } // ignore invalid inputs, e.g. '?&=value' 67 | for (var i = 0; i < h[k].length; i++) { 68 | search += search == "?" ? "" : "&"; 69 | search += encodeURIComponent(k) + "=" + encodeURIComponent(h[k][i]); 70 | } 71 | } 72 | return search; 73 | } 74 | -------------------------------------------------------------------------------- /tests/testapp/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | """Create models in database.""" 2 | 3 | from django.db import migrations, models 4 | import django.db.models.deletion 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | initial = True 10 | 11 | dependencies = [ 12 | ] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name='Book', 17 | fields=[ 18 | ('isbn', models.IntegerField(primary_key=True, serialize=False)), 19 | ('title', models.CharField(max_length=100)), 20 | ], 21 | ), 22 | migrations.CreateModel( 23 | name='Collection', 24 | fields=[ 25 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 26 | ('name', models.CharField(max_length=100)), 27 | ], 28 | ), 29 | migrations.CreateModel( 30 | name='Food', 31 | fields=[ 32 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 33 | ('name', models.CharField(max_length=100)), 34 | ], 35 | ), 36 | migrations.CreateModel( 37 | name='Person', 38 | fields=[ 39 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 40 | ('name', models.CharField(max_length=100)), 41 | ('best_friend', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='testapp.Person')), 42 | ('twin', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rev_twin', to='testapp.person')), 43 | ('curated_collections', models.ManyToManyField(blank=True, to='testapp.Collection')), 44 | ('favorite_book', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='people_with_this_fav_book', to='testapp.Book')), 45 | ('favorite_food', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='testapp.Food')), 46 | ('least_favorite_food', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='food_is_least_fav', related_query_name='people_with_this_least_fav_food', to='testapp.Food')), 47 | ('siblings', models.ManyToManyField(blank=True, related_name='_person_siblings_+', to='testapp.Person')), 48 | ], 49 | ), 50 | migrations.AddField( 51 | model_name='collection', 52 | name='curators', 53 | field=models.ManyToManyField(blank=True, to='testapp.Person'), 54 | ), 55 | migrations.AddField( 56 | model_name='book', 57 | name='author', 58 | field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='testapp.Person'), 59 | ), 60 | migrations.AddField( 61 | model_name='book', 62 | name='coll', 63 | field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='testapp.Collection'), 64 | ), 65 | ] 66 | -------------------------------------------------------------------------------- /tests/testapp/tests.py: -------------------------------------------------------------------------------- 1 | """Define tests for the test app.""" 2 | 3 | import json 4 | from django.contrib.admin.utils import flatten 5 | from django.contrib.auth.models import User 6 | from django.core import exceptions 7 | from django.test import TestCase, tag 8 | from django.urls import reverse 9 | from admin_auto_filters import filters 10 | from tests.testapp.admin import BASIC_USERNAME, SHORTCUT_USERNAME 11 | from tests.testapp.models import Food, Collection, Person, Book 12 | 13 | 14 | def name(model): 15 | """A repeatable way to get the formatted model name.""" 16 | return model.__name__.replace('_', '').lower() 17 | 18 | 19 | # a all of the models, and their names for convenience 20 | MODELS = (Food, Collection, Person, Book) 21 | MODEL_NAMES = tuple([name(model) for model in MODELS]) 22 | 23 | 24 | # a tuple of tuples with (model_name, key, val, field, pks) 25 | # this must match data in fixture 26 | FILTER_STRINGS = ( 27 | (Food, 'person', '3', 'id', (3,)), 28 | (Food, 'people_with_this_least_fav_food', '3', 'id', (2,)), 29 | (Collection, 'curators', '1', 'id', (1,)), 30 | (Collection, 'curators', '3', 'id', ()), 31 | (Collection, 'book', '2357', 'id', (2,)), 32 | (Person, 'best_friend', '1', 'id', (2, 3)), 33 | (Person, 'twin', '1', 'id', (3,)), 34 | (Person, 'rev_twin', '3', 'id', (1,)), 35 | (Person, 'best_friend__best_friend', '1', 'id', (4,)), 36 | (Person, 'best_friend__favorite_food', '1', 'id', (4,)), 37 | (Person, 'siblings', '2', 'id', (1, 3, 4)), 38 | (Person, 'favorite_food', '3', 'id', (3, 4)), 39 | (Person, 'person', '3', 'id', (1,)), 40 | (Person, 'book', '1111', 'id', (4,)), 41 | (Person, 'person__favorite_food', '3', 'id', (1,2)), 42 | (Person, 'collection', '1', 'id', (1, 2)), 43 | (Book, 'author', '2', 'isbn', (42,)), 44 | (Book, 'coll', '2', 'isbn', (2357,)), 45 | (Book, 'people_with_this_fav_book', '4', 'isbn', (1234,)), 46 | ) 47 | 48 | 49 | class RootTestCase(object): 50 | # fixtures = ['fixture.json'] # loading from data migration 0002 51 | 52 | @classmethod 53 | def setUpTestData(cls): 54 | cls.basic_user = User.objects.get(username=BASIC_USERNAME) 55 | cls.shortcut_user = User.objects.get(username=SHORTCUT_USERNAME) 56 | 57 | def test_endpoint(self): 58 | """ 59 | Test that custom autocomplete endpoint functions and returns proper values. 60 | """ 61 | url = reverse('admin:foods_that_are_favorites') 62 | response = self.client.get(url, follow=False) 63 | self.assertEqual(response.status_code, 200, msg=str(url)) 64 | data = json.loads(response.content) 65 | texts = set([item['text'] for item in data['results']]) 66 | self.assertEqual(len(texts), 2, msg=str(texts)) 67 | self.assertIn('SPAM', texts, msg=str(texts)) 68 | self.assertIn('TOAST', texts, msg=str(texts)) 69 | 70 | def test_admin_changelist_search(self): 71 | """ 72 | Test that the admin changelist page loads with a search query, at a basic level. 73 | Need selenium tests to fully check. 74 | """ 75 | for model_name in MODEL_NAMES: 76 | with self.subTest(model_name=model_name): 77 | url = reverse('admin:testapp_%s_changelist' % model_name) + '?q=a' 78 | response = self.client.get(url, follow=False) 79 | self.assertContains( 80 | response, '/static/custom.css', 81 | html=False, msg_prefix=str(url) 82 | ) 83 | 84 | def test_admin_autocomplete_load(self): 85 | """ 86 | Test that the admin autocomplete endpoint loads. 87 | """ 88 | for model_name in MODEL_NAMES: 89 | with self.subTest(model_name=model_name): 90 | url = reverse('admin:testapp_%s_autocomplete' % model_name) 91 | response = self.client.get(url, follow=False) 92 | self.assertContains(response, '"results"') 93 | 94 | def test_admin_changelist_filters(self): 95 | """ 96 | Test that the admin changelist page loads with filters applied, at a basic level. 97 | Need selenium tests to fully check. 98 | """ 99 | for model, key, val, field, pks in FILTER_STRINGS: 100 | model_name = name(model) 101 | with self.subTest(model_name=model_name, key=key, val=val, field=field): 102 | url = reverse('admin:testapp_%s_changelist' % model_name) + '?%s=%s' % (key, val) 103 | response = self.client.get(url, follow=False) 104 | # print(response.content.decode('utf-8')) 105 | self.assertEqual(response.status_code, 200, msg=str(url)) 106 | all_pks = set(flatten(list(model.objects.values_list('pk')))) 107 | for pk in pks: 108 | self.assertContains( 109 | response, '%s' % (field, pk), 110 | html=True, msg_prefix=str(url) 111 | ) 112 | for pk in all_pks - set(pks): 113 | self.assertNotContains( 114 | response, '%s' % (field, pk), 115 | html=True, msg_prefix=str(url) 116 | ) 117 | 118 | def test_get_queryset_for_field(self): 119 | """ 120 | Test the AutocompleteFilter.get_queryset_for_field method. 121 | """ 122 | class TestFilter(filters.AutocompleteFilter): 123 | def __init__(self, *args, **kwargs): 124 | pass 125 | f = TestFilter() 126 | self.assertRaises(exceptions.FieldDoesNotExist, 127 | f.get_queryset_for_field, Person, 'not_a_field') 128 | self.assertRaises(AttributeError, 129 | f.get_queryset_for_field, Person, 'name') 130 | for field in ('best_friend', 'siblings', 'favorite_food', 131 | 'curated_collections', 'favorite_book', 'book'): 132 | with self.subTest(field=field): 133 | try: 134 | qs = f.get_queryset_for_field(Person, field) 135 | except BaseException as e: 136 | self.fail(str(e)) 137 | try: 138 | qs = f.get_queryset_for_field(Book, 'people_with_this_fav_book') 139 | except BaseException as e: 140 | self.fail(str(e)) 141 | 142 | 143 | @tag('basic') 144 | class BasicTestCase(RootTestCase, TestCase): 145 | def setUp(self): 146 | self.client.force_login(self.basic_user) 147 | 148 | 149 | @tag('shortcut') 150 | class ShortcutTestCase(RootTestCase, TestCase): 151 | def setUp(self): 152 | self.client.force_login(self.shortcut_user) 153 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![PyPI version](https://badge.fury.io/py/django-admin-autocomplete-filter.svg?kill_cache=1)](https://badge.fury.io/py/django-admin-autocomplete-filter) 2 | 3 | 4 | Django Admin Autocomplete Filter 5 | ================================ 6 | A simple Django app to render list filters in django admin using an autocomplete widget. This app is heavily inspired by [dal-admin-filters.](https://github.com/shamanu4/dal_admin_filters) 7 | 8 | 9 | Overview: 10 | --------- 11 | 12 | Django comes preshipped with an admin panel which is a great utility to create quick CRUD's. 13 | Version 2.0 came with a much needed [`autocomplete_fields`](https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields "autocomplete_fields") property which uses a select2 widget to load the options asynchronously. We leverage this in `django-admin-list-filter`. 14 | 15 | 16 | 17 | Requirements: 18 | ------------- 19 | 20 | Requires Django version >= 2.0 21 | 22 | 23 | Features: 24 | ------------- 25 | 26 | * Custom search view/endpoint ([more details](#functionality-to-provide-custom-view-for-search)) 27 | * `list_filter` Filter Factory support ([more details](#shortcut-for-creating-filters)) 28 | * Custom widget text ([more details](#customizing-widget-text)) 29 | * Support for [Grappelli](https://grappelliproject.com/) 30 | 31 | 32 | Installation: 33 | ------------- 34 | 35 | You can install it via pip. To get the latest version clone this repo. 36 | 37 | ```shell script 38 | pip install django-admin-autocomplete-filter 39 | ``` 40 | 41 | Add `admin_auto_filters` to your `INSTALLED_APPS` inside settings.py of your project. 42 | 43 | 44 | Usage: 45 | ------ 46 | 47 | Let's say we have following models: 48 | ```python 49 | from django.db import models 50 | 51 | class Artist(models.Model): 52 | name = models.CharField(max_length=128) 53 | 54 | class Album(models.Model): 55 | name = models.CharField(max_length=64) 56 | artist = models.ForeignKey(Artist, on_delete=models.CASCADE) 57 | cover = models.CharField(max_length=256, null=True, default=None) 58 | ``` 59 | 60 | And you would like to filter results in `AlbumAdmin` on the basis of `artist`. You need to define `search fields` in `Artist` and then define filter like this: 61 | 62 | ```python 63 | from django.contrib import admin 64 | from admin_auto_filters.filters import AutocompleteFilter 65 | 66 | 67 | class ArtistFilter(AutocompleteFilter): 68 | title = 'Artist' # display title 69 | field_name = 'artist' # name of the foreign key field 70 | 71 | 72 | class ArtistAdmin(admin.ModelAdmin): 73 | search_fields = ['name'] # this is required for django's autocomplete functionality 74 | # ... 75 | 76 | 77 | class AlbumAdmin(admin.ModelAdmin): 78 | list_filter = [ArtistFilter] 79 | # ... 80 | ``` 81 | 82 | After following these steps you may see the filter as: 83 | 84 | ![](https://raw.githubusercontent.com/farhan0581/django-admin-autocomplete-filter/master/admin_auto_filters/media/screenshot1.png) 85 | 86 | ![](https://raw.githubusercontent.com/farhan0581/django-admin-autocomplete-filter/master/admin_auto_filters/media/screenshot2.png) 87 | 88 | 89 | Functionality to provide a custom view for search: 90 | -------------------------------------------------- 91 | 92 | You can also register your custom view instead of using Django admin's `search_results` to control the results in the autocomplete. For this you will need to create your custom view and register the URL in your admin class as shown below: 93 | 94 | In your `views.py`: 95 | 96 | ```python 97 | from admin_auto_filters.views import AutocompleteJsonView 98 | 99 | 100 | class CustomSearchView(AutocompleteJsonView): 101 | def get_queryset(self): 102 | """ 103 | your custom logic goes here. 104 | """ 105 | queryset = super().get_queryset() 106 | queryset = queryset.order_by('name') 107 | return queryset 108 | ``` 109 | 110 | After this, register this view in your admin class: 111 | 112 | ```python 113 | from django.contrib import admin 114 | from django.urls import path 115 | 116 | 117 | class AlbumAdmin(admin.ModelAdmin): 118 | list_filter = [ArtistFilter] 119 | 120 | def get_urls(self): 121 | urls = super().get_urls() 122 | custom_urls = [ 123 | path('custom_search/', self.admin_site.admin_view(CustomSearchView.as_view(model_admin=self)), 124 | name='custom_search'), 125 | ] 126 | return custom_urls + urls 127 | ``` 128 | 129 | Finally, just tell the filter class to use this new view: 130 | 131 | ```python 132 | from django.shortcuts import reverse 133 | from admin_auto_filters.filters import AutocompleteFilter 134 | 135 | 136 | class ArtistFilter(AutocompleteFilter): 137 | title = 'Artist' 138 | field_name = 'artist' 139 | 140 | def get_autocomplete_url(self, request, model_admin): 141 | return reverse('admin:custom_search') 142 | ``` 143 | 144 | 145 | Shortcut for creating filters: 146 | ------------------------------ 147 | 148 | It's also possible to use the `AutocompleteFilterFactory` shortcut to create 149 | filters on the fly, as shown below. Nested relations are supported too, with 150 | no need to specify the model. 151 | 152 | ```python 153 | from django.contrib import admin 154 | from admin_auto_filters.filters import AutocompleteFilterFactory 155 | 156 | 157 | class AlbumAdmin(admin.ModelAdmin): 158 | list_filter = [ 159 | AutocompleteFilterFactory('Artist', 'artist', 'admin:custom_search', True) 160 | ] 161 | 162 | def get_urls(self): 163 | """As above...""" 164 | ``` 165 | 166 | 167 | Customizing widget text 168 | ----------------------- 169 | 170 | You can customize the text displayed in the filter widget, to use something 171 | other than `str(obj)`. This needs to be configured for both the dropdown 172 | endpoint and the widget itself. 173 | 174 | In your `views.py`, override `display_text`: 175 | 176 | ```python 177 | from admin_auto_filters.views import AutocompleteJsonView 178 | 179 | 180 | class CustomSearchView(AutocompleteJsonView): 181 | 182 | @staticmethod 183 | def display_text(obj): 184 | return obj.my_str_method() 185 | 186 | def get_queryset(self): 187 | """As above...""" 188 | ``` 189 | 190 | Then use either of two options to customize the text. 191 | 192 | Option one is to specify the form_field in an AutocompleteFilter in your 193 | `admin.py`: 194 | 195 | ```python 196 | from django import forms 197 | from django.contrib import admin 198 | from django.shortcuts import reverse 199 | from admin_auto_filters.filters import AutocompleteFilter 200 | 201 | 202 | class FoodChoiceField(forms.ModelChoiceField): 203 | def label_from_instance(self, obj): 204 | return obj.my_str_method() 205 | 206 | 207 | class ArtistFilter(AutocompleteFilter): 208 | title = 'Artist' 209 | field_name = 'artist' 210 | form_field = FoodChoiceField 211 | 212 | def get_autocomplete_url(self, request, model_admin): 213 | return reverse('admin:custom_search') 214 | 215 | 216 | class AlbumAdmin(admin.ModelAdmin): 217 | list_filter = [ArtistFilter] 218 | 219 | def get_urls(self): 220 | """As above...""" 221 | ``` 222 | 223 | Option two is to use an AutocompleteFilterFactory in your `admin.py` 224 | add a `label_by` argument: 225 | 226 | ```python 227 | from django.contrib import admin 228 | from admin_auto_filters.filters import AutocompleteFilterFactory 229 | 230 | 231 | class AlbumAdmin(admin.ModelAdmin): 232 | list_filter = [ 233 | AutocompleteFilterFactory('Artist', 'artist', 'admin:custom_search', True, label_by='my_str_method') 234 | ] 235 | 236 | def get_urls(self): 237 | """As above...""" 238 | ``` 239 | 240 | 241 | Contributing: 242 | ------------ 243 | 244 | This project is a combined effort of a lot of selfless developers who try to make things easier. Your contribution is most welcome. 245 | 246 | Please make a pull-request to the branch `pre_release`, make sure your branch does not have any conflicts, and clearly mention the problems or improvements your PR is addressing. 247 | 248 | 249 | License: 250 | -------- 251 | 252 | Django Admin Autocomplete Filter is an Open Source project licensed under the terms of the GNU GENERAL PUBLIC LICENSE. 253 | -------------------------------------------------------------------------------- /admin_auto_filters/filters.py: -------------------------------------------------------------------------------- 1 | from django.contrib.admin.widgets import AutocompleteSelect as Base 2 | from django import forms 3 | from django.contrib import admin 4 | from django.db.models.fields.related import ForeignObjectRel 5 | from django.db.models.constants import LOOKUP_SEP # this is '__' 6 | from django.db.models.fields.related_descriptors import ReverseManyToOneDescriptor, ManyToManyDescriptor 7 | from django.forms.widgets import Media, MEDIA_TYPES, media_property 8 | from django.shortcuts import reverse 9 | from django import VERSION as DJANGO_VERSION 10 | 11 | class AutocompleteSelect(Base): 12 | def __init__(self, rel, admin_site, attrs=None, choices=(), using=None, custom_url=None): 13 | self.custom_url = custom_url 14 | super().__init__(rel, admin_site, attrs, choices, using) 15 | 16 | def get_url(self): 17 | return self.custom_url if self.custom_url else super().get_url() 18 | 19 | 20 | class AutocompleteFilter(admin.SimpleListFilter): 21 | template = 'django-admin-autocomplete-filter/autocomplete-filter.html' 22 | title = '' 23 | field_name = '' 24 | field_pk = 'pk' 25 | use_pk_exact = True 26 | is_placeholder_title = False 27 | widget_attrs = {} 28 | rel_model = None 29 | parameter_name = None 30 | form_field = forms.ModelChoiceField 31 | 32 | class Media: 33 | js = ( 34 | 'admin/js/jquery.init.js', 35 | 'django-admin-autocomplete-filter/js/autocomplete_filter_qs.js', 36 | ) 37 | css = { 38 | 'screen': ( 39 | 'django-admin-autocomplete-filter/css/autocomplete-fix.css', 40 | ), 41 | } 42 | 43 | def __init__(self, request, params, model, model_admin): 44 | if self.parameter_name is None: 45 | self.parameter_name = self.field_name 46 | if self.use_pk_exact: 47 | self.parameter_name += '__{}__exact'.format(self.field_pk) 48 | super().__init__(request, params, model, model_admin) 49 | 50 | if self.rel_model: 51 | model = self.rel_model 52 | 53 | if DJANGO_VERSION >= (3, 2): 54 | remote_field = model._meta.get_field(self.field_name) 55 | else: 56 | remote_field = model._meta.get_field(self.field_name).remote_field 57 | 58 | widget = AutocompleteSelect(remote_field, 59 | model_admin.admin_site, 60 | custom_url=self.get_autocomplete_url(request, model_admin),) 61 | form_field = self.get_form_field() 62 | field = form_field( 63 | queryset=self.get_queryset_for_field(model, self.field_name), 64 | widget=widget, 65 | required=False, 66 | ) 67 | 68 | self._add_media(model_admin, widget) 69 | 70 | attrs = self.widget_attrs.copy() 71 | attrs['id'] = 'id-%s-dal-filter' % self.parameter_name 72 | if self.is_placeholder_title: 73 | # Upper case letter P as dirty hack for bypass django2 widget force placeholder value as empty string ("") 74 | attrs['data-Placeholder'] = self.title 75 | self.rendered_widget = field.widget.render( 76 | name=self.parameter_name, 77 | value=self.used_parameters.get(self.parameter_name, ''), 78 | attrs=attrs 79 | ) 80 | 81 | @staticmethod 82 | def get_queryset_for_field(model, name): 83 | try: 84 | field_desc = getattr(model, name) 85 | except AttributeError: 86 | field_desc = model._meta.get_field(name) 87 | if isinstance(field_desc, ManyToManyDescriptor): 88 | related_model = field_desc.rel.related_model if field_desc.reverse else field_desc.rel.model 89 | elif isinstance(field_desc, ReverseManyToOneDescriptor): 90 | related_model = field_desc.rel.related_model # look at field_desc.related_manager_cls()? 91 | elif isinstance(field_desc, ForeignObjectRel): 92 | # includes ManyToOneRel, ManyToManyRel 93 | # also includes OneToOneRel - not sure how this would be used 94 | related_model = field_desc.related_model 95 | else: 96 | # primarily for ForeignKey/ForeignKeyDeferredAttribute 97 | # also includes ForwardManyToOneDescriptor, ForwardOneToOneDescriptor, ReverseOneToOneDescriptor 98 | return field_desc.get_queryset() 99 | return related_model.objects.get_queryset() 100 | 101 | def get_form_field(self): 102 | """Return the type of form field to be used.""" 103 | return self.form_field 104 | 105 | def _add_media(self, model_admin, widget): 106 | 107 | if not hasattr(model_admin, 'Media'): 108 | model_admin.__class__.Media = type('Media', (object,), dict()) 109 | model_admin.__class__.media = media_property(model_admin.__class__) 110 | 111 | def _get_media(obj): 112 | return Media(media=getattr(obj, 'Media', None)) 113 | 114 | media = _get_media(model_admin) + widget.media + _get_media(AutocompleteFilter) + _get_media(self) 115 | 116 | for name in MEDIA_TYPES: 117 | setattr(model_admin.Media, name, getattr(media, "_" + name)) 118 | 119 | def has_output(self): 120 | return True 121 | 122 | def lookups(self, request, model_admin): 123 | return () 124 | 125 | def queryset(self, request, queryset): 126 | if self.value(): 127 | return queryset.filter(**{self.parameter_name: self.value()}) 128 | else: 129 | return queryset 130 | 131 | def get_autocomplete_url(self, request, model_admin): 132 | ''' 133 | Hook to specify your custom view for autocomplete, 134 | instead of default django admin's search_results. 135 | ''' 136 | return None 137 | 138 | 139 | def generate_choice_field(label_item): 140 | """ 141 | Create a ModelChoiceField variant with a modified label_from_instance. 142 | Note that label_item can be a callable, or a model field, or a model callable. 143 | """ 144 | class LabelledModelChoiceField(forms.ModelChoiceField): 145 | def label_from_instance(self, obj): 146 | if callable(label_item): 147 | value = label_item(obj) 148 | elif hasattr(obj, str(label_item)): 149 | attr = getattr(obj, label_item) 150 | if callable(attr): 151 | value = attr() 152 | else: 153 | value = attr 154 | else: 155 | raise ValueError('Invalid label_item specified: %s' % str(label_item)) 156 | return value 157 | return LabelledModelChoiceField 158 | 159 | 160 | def _get_rel_model(model, parameter_name): 161 | """ 162 | A way to calculate the model for a parameter_name that includes LOOKUP_SEP. 163 | """ 164 | field_names = str(parameter_name).split(LOOKUP_SEP) 165 | if len(field_names) == 1: 166 | return None 167 | else: 168 | rel_model = model 169 | for name in field_names[:-1]: 170 | rel_model = rel_model._meta.get_field(name).related_model 171 | return rel_model 172 | 173 | 174 | def AutocompleteFilterFactory(title, base_parameter_name, viewname='', use_pk_exact=False, label_by=str): 175 | """ 176 | An autocomplete widget filter with a customizable title. Use like this: 177 | AutocompleteFilterFactory('My title', 'field_name') 178 | AutocompleteFilterFactory('My title', 'fourth__third__second__first') 179 | Be sure to include distinct in the model admin get_queryset() if the second form is used. 180 | Assumes: parameter_name == f'fourth__third__second__{field_name}' 181 | * title: The title for the filter. 182 | * base_parameter_name: The field to use for the filter. 183 | * viewname: The name of the custom AutocompleteJsonView URL to use, if any. 184 | * use_pk_exact: Whether to use '__pk__exact' in the parameter name when possible. 185 | * label_by: How to generate the static label for the widget - a callable, the name 186 | of a model callable, or the name of a model field. 187 | """ 188 | 189 | class NewMetaFilter(type(AutocompleteFilter)): 190 | """A metaclass for an autogenerated autocomplete filter class.""" 191 | 192 | def __new__(cls, name, bases, attrs): 193 | super_new = super().__new__(cls, name, bases, attrs) 194 | super_new.use_pk_exact = use_pk_exact 195 | field_names = str(base_parameter_name).split(LOOKUP_SEP) 196 | super_new.field_name = field_names[-1] 197 | super_new.parameter_name = base_parameter_name 198 | if len(field_names) <= 1 and super_new.use_pk_exact: 199 | super_new.parameter_name += '__{}__exact'.format(super_new.field_pk) 200 | return super_new 201 | 202 | class NewFilter(AutocompleteFilter, metaclass=NewMetaFilter): 203 | """An autogenerated autocomplete filter class.""" 204 | 205 | def __init__(self, request, params, model, model_admin): 206 | self.rel_model = _get_rel_model(model, base_parameter_name) 207 | self.form_field = generate_choice_field(label_by) 208 | super().__init__(request, params, model, model_admin) 209 | self.title = title 210 | 211 | def get_autocomplete_url(self, request, model_admin): 212 | if viewname == '': 213 | return super().get_autocomplete_url(request, model_admin) 214 | else: 215 | return reverse(viewname) 216 | 217 | return NewFilter 218 | -------------------------------------------------------------------------------- /tests/testapp/admin.py: -------------------------------------------------------------------------------- 1 | """Defines the admin interface for the test app, including inlines and filters.""" 2 | 3 | from django import forms 4 | from django.contrib import admin 5 | from django.shortcuts import reverse 6 | from django.urls import path 7 | from admin_auto_filters.filters import AutocompleteFilter, AutocompleteFilterFactory 8 | from .models import Food, Person, Collection, Book 9 | from .views import FoodsThatAreFavorites 10 | 11 | 12 | # hard code some user constants (must match fixture) 13 | BASIC_USERNAME = 'bu' # password is 'bu' 14 | SHORTCUT_USERNAME = 'su' # password is 'su' 15 | 16 | 17 | class PersonFoodFilter(AutocompleteFilter): 18 | title = 'favorite food of person (manual)' 19 | field_name = 'person' 20 | rel_model = Food 21 | parameter_name = 'person' 22 | 23 | 24 | class PersonLeastFavFoodFilter(AutocompleteFilter): 25 | title = 'least favorite food of person (manual)' 26 | field_name = 'people_with_this_least_fav_food' 27 | rel_model = Food 28 | parameter_name = 'people_with_this_least_fav_food' 29 | 30 | 31 | class CuratorsFilter(AutocompleteFilter): 32 | title = 'curators (manual)' 33 | field_name = 'curators' 34 | rel_model = Collection 35 | parameter_name = 'curators' 36 | 37 | 38 | class BookFilter(AutocompleteFilter): 39 | title = 'has book (manual)' 40 | field_name = 'book' 41 | rel_model = Collection 42 | parameter_name = 'book' 43 | 44 | 45 | class FriendFilter(AutocompleteFilter): 46 | title = 'best friend (manual)' 47 | field_name = 'best_friend' 48 | rel_model = Person 49 | parameter_name = 'best_friend' 50 | 51 | 52 | class TwinFilter(AutocompleteFilter): 53 | title = 'twin (manual)' 54 | field_name = 'twin' 55 | rel_model = Person 56 | parameter_name = 'twin' 57 | 58 | 59 | class RevTwinFilter(AutocompleteFilter): 60 | title = 'reverse twin (manual)' 61 | field_name = 'rev_twin' 62 | rel_model = Person 63 | parameter_name = 'rev_twin' 64 | 65 | 66 | class FriendFriendFilter(AutocompleteFilter): 67 | title = 'best friend\'s best friend (manual)' 68 | field_name = 'best_friend' 69 | rel_model = Person 70 | parameter_name = 'best_friend__best_friend' 71 | 72 | 73 | class FriendFoodFilter(AutocompleteFilter): 74 | title = 'best friend\'s favorite food (manual)' 75 | field_name = 'favorite_food' 76 | rel_model = Person 77 | parameter_name = 'best_friend__favorite_food' 78 | 79 | 80 | class SiblingsFilter(AutocompleteFilter): 81 | title = 'siblings (manual)' 82 | field_name = 'siblings' 83 | rel_model = Person 84 | parameter_name = 'siblings' 85 | 86 | 87 | class FoodChoiceField(forms.ModelChoiceField): 88 | def label_from_instance(self, obj): 89 | return obj.alternate_name() 90 | 91 | 92 | class FoodFilter(AutocompleteFilter): 93 | title = 'food (manual)' 94 | field_name = 'favorite_food' 95 | rel_model = Person 96 | parameter_name = 'favorite_food' 97 | form_field = FoodChoiceField 98 | 99 | def get_autocomplete_url(self, request, model_admin): 100 | return reverse('admin:foods_that_are_favorites') 101 | 102 | 103 | class BestFriendOfFilter(AutocompleteFilter): 104 | title = 'best friend of (manual)' 105 | field_name = 'person' 106 | rel_model = Person 107 | parameter_name = 'person' 108 | 109 | 110 | class AuthoredFilter(AutocompleteFilter): 111 | title = 'authored (manual)' 112 | field_name = 'book' 113 | rel_model = Person 114 | parameter_name = 'book' 115 | 116 | 117 | class RevPersonFoodFilter(AutocompleteFilter): 118 | title = 'best friend of person with fav food (manual)' 119 | field_name = 'favorite_food' 120 | rel_model = Person 121 | parameter_name = 'person__favorite_food' 122 | 123 | 124 | class RevCollectionFilter(AutocompleteFilter): 125 | title = 'collections as curator (manual)' 126 | field_name = 'collection' 127 | rel_model = Person 128 | parameter_name = 'collection' 129 | 130 | 131 | class AuthorFilter(AutocompleteFilter): 132 | title = 'author (manual)' 133 | field_name = 'author' 134 | rel_model = Book 135 | parameter_name = 'author' 136 | 137 | 138 | class CollectionFilter(AutocompleteFilter): 139 | title = 'collection (manual)' 140 | field_name = 'coll' 141 | rel_model = Book 142 | parameter_name = 'coll' 143 | 144 | 145 | class PeopleWithFavBookFilter(AutocompleteFilter): 146 | title = 'people with this fav book (manual)' 147 | field_name = 'people_with_this_fav_book' 148 | rel_model = Book 149 | parameter_name = 'people_with_this_fav_book' 150 | 151 | 152 | class FoodInline(admin.TabularInline): 153 | extra = 0 154 | fields = ['id', 'name'] 155 | model = Food 156 | 157 | 158 | class CollectionInline(admin.TabularInline): 159 | extra = 0 160 | fields = ['id', 'name'] 161 | model = Collection 162 | 163 | 164 | class PersonInline(admin.TabularInline): 165 | extra = 0 166 | fields = ['id', 'name'] 167 | model = Person 168 | 169 | 170 | class PersonFavoriteFoodInline(PersonInline): 171 | fk_name = 'favorite_food' 172 | 173 | 174 | class BookInline(admin.TabularInline): 175 | extra = 0 176 | fields = ['isbn', 'title'] 177 | model = Book 178 | 179 | 180 | class CustomAdmin(admin.ModelAdmin): 181 | list_filter_auto = [] 182 | 183 | class Media: 184 | css = {'all': ('custom.css',)} 185 | 186 | def get_list_filter(self, request): 187 | if request.user.username == BASIC_USERNAME: 188 | return self.list_filter 189 | elif request.user.username == SHORTCUT_USERNAME: 190 | return self.list_filter_auto 191 | else: 192 | raise ValueError('Unexpected username.') 193 | 194 | 195 | @admin.register(Food) 196 | class FoodAdmin(CustomAdmin): 197 | fields = ['id', 'name'] 198 | inlines = [PersonFavoriteFoodInline] 199 | list_display = ['id', 'name'] 200 | list_display_links = ['name'] 201 | list_filter = [ 202 | PersonFoodFilter, 203 | PersonLeastFavFoodFilter, 204 | ] 205 | list_filter_auto = [ 206 | AutocompleteFilterFactory('favorite food of person (auto)', 'person'), 207 | AutocompleteFilterFactory('least favorite food of person (auto)', 'people_with_this_least_fav_food'), 208 | ] 209 | ordering = ['id'] 210 | readonly_fields = ['id'] 211 | search_fields = ['id', 'name'] 212 | 213 | 214 | @admin.register(Collection) 215 | class CollectionAdmin(CustomAdmin): 216 | autocomplete_fields = ['curators'] 217 | fields = ['id', 'name', 'curators'] 218 | inlines = [BookInline] 219 | list_display = ['id', 'name'] 220 | list_display_links = ['name'] 221 | list_filter = [ 222 | CuratorsFilter, 223 | BookFilter, 224 | ] 225 | list_filter_auto = [ 226 | AutocompleteFilterFactory('curators (auto)', 'curators'), 227 | AutocompleteFilterFactory('has book (auto)', 'book'), 228 | ] 229 | ordering = ['id'] 230 | readonly_fields = ['id'] 231 | search_fields = ['id', 'name', 'curators__name', 232 | 'book__title', 'book__author__name'] 233 | 234 | 235 | @admin.register(Person) 236 | class PersonAdmin(CustomAdmin): 237 | autocomplete_fields = ['best_friend', 'twin', 'siblings', 'favorite_food', 'curated_collections'] 238 | fields = ['id', 'name', 'best_friend', 'twin', 'siblings', 'favorite_food', 'curated_collections'] 239 | inlines = [BookInline] 240 | list_display = ['id', 'name'] 241 | list_display_links = ['name'] 242 | list_filter = [ 243 | FriendFilter, 244 | TwinFilter, 245 | RevTwinFilter, 246 | FriendFriendFilter, 247 | FriendFoodFilter, 248 | SiblingsFilter, 249 | FoodFilter, 250 | BestFriendOfFilter, 251 | AuthoredFilter, 252 | RevPersonFoodFilter, 253 | RevCollectionFilter, 254 | ] 255 | list_filter_auto = [ 256 | AutocompleteFilterFactory('best friend (auto)', 'best_friend'), 257 | AutocompleteFilterFactory('twin (auto)', 'twin'), 258 | AutocompleteFilterFactory('reverse twin (auto)', 'rev_twin'), 259 | AutocompleteFilterFactory('best friend\'s best friend (auto)', 'best_friend__best_friend'), 260 | AutocompleteFilterFactory('best friend\'s favorite food (auto)', 'best_friend__favorite_food'), 261 | AutocompleteFilterFactory('siblings (auto)', 'siblings'), 262 | AutocompleteFilterFactory('food (auto)', 'favorite_food', viewname='admin:foods_that_are_favorites', label_by='alternate_name'), 263 | AutocompleteFilterFactory('best friend of (auto)', 'person'), 264 | AutocompleteFilterFactory('authored (auto)', 'book'), 265 | AutocompleteFilterFactory('best friend of person with fav food (auto)', 'person__favorite_food'), 266 | AutocompleteFilterFactory('collections as curator (auto)', 'collection'), 267 | # AutocompleteFilterFactory('curated_collections (auto)', 'curated_collections'), # does not work... 268 | ] 269 | ordering = ['id'] 270 | readonly_fields = ['id'] 271 | search_fields = ['id', 'name', 'best_friend__name', 272 | 'favorite_food__name', 'siblings__name'] 273 | 274 | def get_urls(self): 275 | urls = super().get_urls() 276 | custom_urls = [ 277 | path('foods_that_are_favorites/', 278 | self.admin_site.admin_view(FoodsThatAreFavorites.as_view(model_admin=self)), 279 | name='foods_that_are_favorites'), 280 | ] 281 | return custom_urls + urls 282 | 283 | 284 | @admin.register(Book) 285 | class BookAdmin(CustomAdmin): 286 | autocomplete_fields = ['author', 'coll'] 287 | fields = ['isbn', 'title', 'author', 'coll'] 288 | inlines = [] 289 | list_display = ['isbn', 'title'] 290 | list_display_links = ['title'] 291 | list_filter = [ 292 | AuthorFilter, 293 | CollectionFilter, 294 | PeopleWithFavBookFilter, 295 | ] 296 | list_filter_auto = [ 297 | AutocompleteFilterFactory('author (auto)', 'author'), 298 | AutocompleteFilterFactory('collection (auto)', 'coll'), 299 | AutocompleteFilterFactory('people with this fav book (auto)', 'people_with_this_fav_book'), 300 | ] 301 | ordering = ['isbn'] 302 | search_fields = ['isbn', 'title', 'author__name', 'coll__name'] 303 | -------------------------------------------------------------------------------- /tests/testapp/fixtures/fixture.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "fields": { 4 | "app_label": "admin", 5 | "model": "logentry" 6 | }, 7 | "model": "contenttypes.contenttype", 8 | "pk": 1 9 | }, 10 | { 11 | "fields": { 12 | "app_label": "auth", 13 | "model": "permission" 14 | }, 15 | "model": "contenttypes.contenttype", 16 | "pk": 2 17 | }, 18 | { 19 | "fields": { 20 | "app_label": "auth", 21 | "model": "group" 22 | }, 23 | "model": "contenttypes.contenttype", 24 | "pk": 3 25 | }, 26 | { 27 | "fields": { 28 | "app_label": "auth", 29 | "model": "user" 30 | }, 31 | "model": "contenttypes.contenttype", 32 | "pk": 4 33 | }, 34 | { 35 | "fields": { 36 | "app_label": "contenttypes", 37 | "model": "contenttype" 38 | }, 39 | "model": "contenttypes.contenttype", 40 | "pk": 5 41 | }, 42 | { 43 | "fields": { 44 | "app_label": "sessions", 45 | "model": "session" 46 | }, 47 | "model": "contenttypes.contenttype", 48 | "pk": 6 49 | }, 50 | { 51 | "fields": { 52 | "app_label": "testapp", 53 | "model": "food" 54 | }, 55 | "model": "contenttypes.contenttype", 56 | "pk": 7 57 | }, 58 | { 59 | "fields": { 60 | "app_label": "testapp", 61 | "model": "person" 62 | }, 63 | "model": "contenttypes.contenttype", 64 | "pk": 8 65 | }, 66 | { 67 | "fields": { 68 | "app_label": "testapp", 69 | "model": "collection" 70 | }, 71 | "model": "contenttypes.contenttype", 72 | "pk": 9 73 | }, 74 | { 75 | "fields": { 76 | "app_label": "testapp", 77 | "model": "book" 78 | }, 79 | "model": "contenttypes.contenttype", 80 | "pk": 10 81 | }, 82 | { 83 | "fields": { 84 | "password": "pbkdf2_sha256$150000$P61yc6fuy5WM$tpxMlJZIOmR9mAKMuw9z2gY/7YgIMFd8hTExNpzuQ34=", 85 | "last_login": null, 86 | "is_superuser": true, 87 | "username": "bu", 88 | "first_name": "", 89 | "last_name": "", 90 | "email": "", 91 | "is_staff": true, 92 | "is_active": true, 93 | "date_joined": "2020-01-01T00:00:01.000Z", 94 | "groups": [], 95 | "user_permissions": [] 96 | }, 97 | "model": "auth.user", 98 | "pk": 1 99 | }, 100 | { 101 | "fields": { 102 | "password": "pbkdf2_sha256$150000$YvNViPfVPtMJ$3gMS8eNwRQ8m9Xe81Z26U0wux9IlMQtl9ze/s1ma84s=", 103 | "last_login": null, 104 | "is_superuser": true, 105 | "username": "su", 106 | "first_name": "", 107 | "last_name": "", 108 | "email": "", 109 | "is_staff": true, 110 | "is_active": true, 111 | "date_joined": "2020-01-01T00:00:02.000Z", 112 | "groups": [], 113 | "user_permissions": [] 114 | }, 115 | "model": "auth.user", 116 | "pk": 2 117 | }, 118 | { 119 | "fields": { 120 | "name": "Spam" 121 | }, 122 | "model": "testapp.food", 123 | "pk": 1 124 | }, 125 | { 126 | "fields": { 127 | "name": "Eggs" 128 | }, 129 | "model": "testapp.food", 130 | "pk": 2 131 | }, 132 | { 133 | "fields": { 134 | "name": "Toast" 135 | }, 136 | "model": "testapp.food", 137 | "pk": 3 138 | }, 139 | { 140 | "fields": { 141 | "name": "Tomatoes" 142 | }, 143 | "model": "testapp.food", 144 | "pk": 4 145 | }, 146 | { 147 | "fields": { 148 | "name": "Coffee" 149 | }, 150 | "model": "testapp.food", 151 | "pk": 5 152 | }, 153 | { 154 | "fields": { 155 | "best_friend": null, 156 | "favorite_food": null, 157 | "name": "Alice", 158 | "siblings": [ 159 | 2 160 | ] 161 | }, 162 | "model": "testapp.person", 163 | "pk": 1 164 | }, 165 | { 166 | "fields": { 167 | "best_friend": 1, 168 | "favorite_food": 1, 169 | "least_favorite_food": 3, 170 | "name": "Bob", 171 | "siblings": [ 172 | 1, 173 | 3 174 | ] 175 | }, 176 | "model": "testapp.person", 177 | "pk": 2 178 | }, 179 | { 180 | "fields": { 181 | "best_friend": 1, 182 | "favorite_food": 3, 183 | "least_favorite_food": 2, 184 | "twin": 1, 185 | "name": "Carol" 186 | }, 187 | "model": "testapp.person", 188 | "pk": 3 189 | }, 190 | { 191 | "fields": { 192 | "best_friend": 2, 193 | "favorite_book": 1234, 194 | "favorite_food": 3, 195 | "name": "David", 196 | "siblings": [ 197 | 2 198 | ] 199 | }, 200 | "model": "testapp.person", 201 | "pk": 4 202 | }, 203 | { 204 | "fields": { 205 | "curators": [ 206 | 1, 207 | 2 208 | ], 209 | "name": "Library" 210 | }, 211 | "model": "testapp.collection", 212 | "pk": 1 213 | }, 214 | { 215 | "fields": { 216 | "curators": [ 217 | 2 218 | ], 219 | "name": "Bookstore" 220 | }, 221 | "model": "testapp.collection", 222 | "pk": 2 223 | }, 224 | { 225 | "fields": { 226 | "author": 1, 227 | "coll": 1, 228 | "title": "The Funniest Joke in the World" 229 | }, 230 | "model": "testapp.book", 231 | "pk": 1234 232 | }, 233 | { 234 | "fields": { 235 | "author": 2, 236 | "coll": 1, 237 | "title": "Fish-Slapping Dances" 238 | }, 239 | "model": "testapp.book", 240 | "pk": 42 241 | }, 242 | { 243 | "fields": { 244 | "author": 4, 245 | "coll": 2, 246 | "title": "The Meaning of Life" 247 | }, 248 | "model": "testapp.book", 249 | "pk": 2357 250 | }, 251 | { 252 | "fields": { 253 | "author": 4, 254 | "coll": 1, 255 | "title": "Camelot" 256 | }, 257 | "model": "testapp.book", 258 | "pk": 1111 259 | }, 260 | { 261 | "fields": { 262 | "codename": "add_logentry", 263 | "content_type": 1, 264 | "name": "Can add log entry" 265 | }, 266 | "model": "auth.permission", 267 | "pk": 1 268 | }, 269 | { 270 | "fields": { 271 | "codename": "change_logentry", 272 | "content_type": 1, 273 | "name": "Can change log entry" 274 | }, 275 | "model": "auth.permission", 276 | "pk": 2 277 | }, 278 | { 279 | "fields": { 280 | "codename": "delete_logentry", 281 | "content_type": 1, 282 | "name": "Can delete log entry" 283 | }, 284 | "model": "auth.permission", 285 | "pk": 3 286 | }, 287 | { 288 | "fields": { 289 | "codename": "view_logentry", 290 | "content_type": 1, 291 | "name": "Can view log entry" 292 | }, 293 | "model": "auth.permission", 294 | "pk": 4 295 | }, 296 | { 297 | "fields": { 298 | "codename": "add_permission", 299 | "content_type": 2, 300 | "name": "Can add permission" 301 | }, 302 | "model": "auth.permission", 303 | "pk": 5 304 | }, 305 | { 306 | "fields": { 307 | "codename": "change_permission", 308 | "content_type": 2, 309 | "name": "Can change permission" 310 | }, 311 | "model": "auth.permission", 312 | "pk": 6 313 | }, 314 | { 315 | "fields": { 316 | "codename": "delete_permission", 317 | "content_type": 2, 318 | "name": "Can delete permission" 319 | }, 320 | "model": "auth.permission", 321 | "pk": 7 322 | }, 323 | { 324 | "fields": { 325 | "codename": "view_permission", 326 | "content_type": 2, 327 | "name": "Can view permission" 328 | }, 329 | "model": "auth.permission", 330 | "pk": 8 331 | }, 332 | { 333 | "fields": { 334 | "codename": "add_group", 335 | "content_type": 3, 336 | "name": "Can add group" 337 | }, 338 | "model": "auth.permission", 339 | "pk": 9 340 | }, 341 | { 342 | "fields": { 343 | "codename": "change_group", 344 | "content_type": 3, 345 | "name": "Can change group" 346 | }, 347 | "model": "auth.permission", 348 | "pk": 10 349 | }, 350 | { 351 | "fields": { 352 | "codename": "delete_group", 353 | "content_type": 3, 354 | "name": "Can delete group" 355 | }, 356 | "model": "auth.permission", 357 | "pk": 11 358 | }, 359 | { 360 | "fields": { 361 | "codename": "view_group", 362 | "content_type": 3, 363 | "name": "Can view group" 364 | }, 365 | "model": "auth.permission", 366 | "pk": 12 367 | }, 368 | { 369 | "fields": { 370 | "codename": "add_user", 371 | "content_type": 4, 372 | "name": "Can add user" 373 | }, 374 | "model": "auth.permission", 375 | "pk": 13 376 | }, 377 | { 378 | "fields": { 379 | "codename": "change_user", 380 | "content_type": 4, 381 | "name": "Can change user" 382 | }, 383 | "model": "auth.permission", 384 | "pk": 14 385 | }, 386 | { 387 | "fields": { 388 | "codename": "delete_user", 389 | "content_type": 4, 390 | "name": "Can delete user" 391 | }, 392 | "model": "auth.permission", 393 | "pk": 15 394 | }, 395 | { 396 | "fields": { 397 | "codename": "view_user", 398 | "content_type": 4, 399 | "name": "Can view user" 400 | }, 401 | "model": "auth.permission", 402 | "pk": 16 403 | }, 404 | { 405 | "fields": { 406 | "codename": "add_contenttype", 407 | "content_type": 5, 408 | "name": "Can add content type" 409 | }, 410 | "model": "auth.permission", 411 | "pk": 17 412 | }, 413 | { 414 | "fields": { 415 | "codename": "change_contenttype", 416 | "content_type": 5, 417 | "name": "Can change content type" 418 | }, 419 | "model": "auth.permission", 420 | "pk": 18 421 | }, 422 | { 423 | "fields": { 424 | "codename": "delete_contenttype", 425 | "content_type": 5, 426 | "name": "Can delete content type" 427 | }, 428 | "model": "auth.permission", 429 | "pk": 19 430 | }, 431 | { 432 | "fields": { 433 | "codename": "view_contenttype", 434 | "content_type": 5, 435 | "name": "Can view content type" 436 | }, 437 | "model": "auth.permission", 438 | "pk": 20 439 | }, 440 | { 441 | "fields": { 442 | "codename": "add_session", 443 | "content_type": 6, 444 | "name": "Can add session" 445 | }, 446 | "model": "auth.permission", 447 | "pk": 21 448 | }, 449 | { 450 | "fields": { 451 | "codename": "change_session", 452 | "content_type": 6, 453 | "name": "Can change session" 454 | }, 455 | "model": "auth.permission", 456 | "pk": 22 457 | }, 458 | { 459 | "fields": { 460 | "codename": "delete_session", 461 | "content_type": 6, 462 | "name": "Can delete session" 463 | }, 464 | "model": "auth.permission", 465 | "pk": 23 466 | }, 467 | { 468 | "fields": { 469 | "codename": "view_session", 470 | "content_type": 6, 471 | "name": "Can view session" 472 | }, 473 | "model": "auth.permission", 474 | "pk": 24 475 | }, 476 | { 477 | "fields": { 478 | "codename": "add_food", 479 | "content_type": 7, 480 | "name": "Can add food" 481 | }, 482 | "model": "auth.permission", 483 | "pk": 25 484 | }, 485 | { 486 | "fields": { 487 | "codename": "change_food", 488 | "content_type": 7, 489 | "name": "Can change food" 490 | }, 491 | "model": "auth.permission", 492 | "pk": 26 493 | }, 494 | { 495 | "fields": { 496 | "codename": "delete_food", 497 | "content_type": 7, 498 | "name": "Can delete food" 499 | }, 500 | "model": "auth.permission", 501 | "pk": 27 502 | }, 503 | { 504 | "fields": { 505 | "codename": "view_food", 506 | "content_type": 7, 507 | "name": "Can view food" 508 | }, 509 | "model": "auth.permission", 510 | "pk": 28 511 | }, 512 | { 513 | "fields": { 514 | "codename": "add_person", 515 | "content_type": 8, 516 | "name": "Can add person" 517 | }, 518 | "model": "auth.permission", 519 | "pk": 29 520 | }, 521 | { 522 | "fields": { 523 | "codename": "change_person", 524 | "content_type": 8, 525 | "name": "Can change person" 526 | }, 527 | "model": "auth.permission", 528 | "pk": 30 529 | }, 530 | { 531 | "fields": { 532 | "codename": "delete_person", 533 | "content_type": 8, 534 | "name": "Can delete person" 535 | }, 536 | "model": "auth.permission", 537 | "pk": 31 538 | }, 539 | { 540 | "fields": { 541 | "codename": "view_person", 542 | "content_type": 8, 543 | "name": "Can view person" 544 | }, 545 | "model": "auth.permission", 546 | "pk": 32 547 | }, 548 | { 549 | "fields": { 550 | "codename": "add_collection", 551 | "content_type": 9, 552 | "name": "Can add collection" 553 | }, 554 | "model": "auth.permission", 555 | "pk": 33 556 | }, 557 | { 558 | "fields": { 559 | "codename": "change_collection", 560 | "content_type": 9, 561 | "name": "Can change collection" 562 | }, 563 | "model": "auth.permission", 564 | "pk": 34 565 | }, 566 | { 567 | "fields": { 568 | "codename": "delete_collection", 569 | "content_type": 9, 570 | "name": "Can delete collection" 571 | }, 572 | "model": "auth.permission", 573 | "pk": 35 574 | }, 575 | { 576 | "fields": { 577 | "codename": "view_collection", 578 | "content_type": 9, 579 | "name": "Can view collection" 580 | }, 581 | "model": "auth.permission", 582 | "pk": 36 583 | }, 584 | { 585 | "fields": { 586 | "codename": "add_book", 587 | "content_type": 10, 588 | "name": "Can add book" 589 | }, 590 | "model": "auth.permission", 591 | "pk": 37 592 | }, 593 | { 594 | "fields": { 595 | "codename": "change_book", 596 | "content_type": 10, 597 | "name": "Can change book" 598 | }, 599 | "model": "auth.permission", 600 | "pk": 38 601 | }, 602 | { 603 | "fields": { 604 | "codename": "delete_book", 605 | "content_type": 10, 606 | "name": "Can delete book" 607 | }, 608 | "model": "auth.permission", 609 | "pk": 39 610 | }, 611 | { 612 | "fields": { 613 | "codename": "view_book", 614 | "content_type": 10, 615 | "name": "Can view book" 616 | }, 617 | "model": "auth.permission", 618 | "pk": 40 619 | } 620 | ] 621 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------