Commit d5195dcb authored by Aymeric's avatar Aymeric

Merge branch 'master' of https://gitlab.utc.fr/sr04/pyprevention

parents 7636be4d 86550fe0
No preview for this file type
......@@ -25,7 +25,7 @@ SECRET_KEY = '9)j@^7egsmi)w9xvgi$)ialy)0gfl@874hh@xcn^d^nltx)-c='
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
ALLOWED_HOSTS = ['51.68.125.23','vergnol.eu','www.vergnol.eu','localhost','127.0.0.1',]
# Application definition
......
Copyright (c) 2007 Michael Trier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Metadata-Version: 2.1
Name: django-extensions
Version: 2.1.3
Summary: Extensions for Django
Home-page: http://github.com/django-extensions/django-extensions
Author: Michael Trier
Author-email: mtrier@gmail.com
Maintainer: Bas van Oostveen
Maintainer-email: v.oostveen@gmail.com
License: MIT License
Platform: any
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Framework :: Django
Classifier: Framework :: Django :: 1.11
Classifier: Framework :: Django :: 2.0
Classifier: Framework :: Django :: 2.1
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Topic :: Utilities
Requires-Dist: six (>=1.2)
Requires-Dist: typing; python_version < "3.5"
===================
Django Extensions
===================
.. image:: https://img.shields.io/pypi/l/django-extensions.svg
:target: https://raw.githubusercontent.com/django-extensions/django-extensions/master/LICENSE
.. image:: https://secure.travis-ci.org/django-extensions/django-extensions.svg?branch=master
:alt: Build Status
:target: http://travis-ci.org/django-extensions/django-extensions
.. image:: https://img.shields.io/pypi/v/django-extensions.svg
:target: https://pypi.python.org/pypi/django-extensions/
:alt: Latest PyPI version
.. image:: https://img.shields.io/pypi/wheel/django-extensions.svg
:target: https://pypi.python.org/pypi/django-extensions/
:alt: Supports Wheel format
.. image:: https://coveralls.io/repos/django-extensions/django-extensions/badge.svg?branch=master
:target: https://coveralls.io/r/django-extensions/django-extensions?branch=master
:alt: Coverage
Django Extensions is a collection of custom extensions for the Django Framework.
Getting Started
===============
The easiest way to figure out what Django Extensions are all about is to watch the
`excellent screencast by Eric Holscher`__ (`watch the video on vimeo`__). In a couple
minutes Eric walks you through a half a dozen command extensions. There is also a
`short screencast on GoDjango`__ to help show you even more.
Requirements
============
Django Extensions requires Django 1.11 or later.
Getting It
==========
You can get Django Extensions by using pip::
$ pip install django-extensions
If you want to install it from source, grab the git repository from GitHub and run setup.py::
$ git clone git://github.com/django-extensions/django-extensions.git
$ cd django-extensions
$ python setup.py install
Installing It
=============
To enable `django_extensions` in your project you need to add it to `INSTALLED_APPS` in your projects
`settings.py` file::
INSTALLED_APPS = (
...
'django_extensions',
...
)
Using It
========
Generate (and view) a graphviz graph of app models::
$ python manage.py graph_models -a -o myapp_models.png
Produce a tab-separated list of `(url_pattern, view_function, name)` tuples for a project::
$ python manage.py show_urls
Check templates for rendering errors::
$ python manage.py validate_templates
Run the enhanced django shell::
$ python manage.py shell_plus
Run the enhanced django runserver, (requires Werkzeug install)::
$ python manage.py runserver_plus
Getting Involved
================
Open Source projects can always use more help. Fixing a problem, documenting a feature, adding
translation in your language. If you have some time to spare and like to help us, here are the places to do so:
- GitHub: https://github.com/django-extensions/django-extensions
- Mailing list: http://groups.google.com/group/django-extensions
- Translations: https://www.transifex.net/projects/p/django-extensions/
Documentation
=============
You can view documentation online at:
- https://django-extensions.readthedocs.io
Or you can look at the docs/ directory in the repository.
Support
=======
Django Extensions is free and always will be. It is development and maintained by developers in an Open Source manner.
Any support is welcome. You could help by writing documentation, pull-requests, report issues and/or translations.
Please remember that nobody is paid directly to develop or maintain Django Extensions so we do have to divide our time
between putting food on the table, family, this project and the rest of life :-)
__ http://ericholscher.com/blog/2008/sep/12/screencast-django-command-extensions/
__ http://vimeo.com/1720508
__ https://godjango.com/39-be-more-productive-with-django_extensions/
Wheel-Version: 1.0
Generator: bdist_wheel (0.32.0)
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any
# -*- coding: utf-8 -*-
VERSION = (2, 1, 3)
# Dynamically calculate the version based on VERSION tuple
if len(VERSION) > 2 and VERSION[2] is not None:
if isinstance(VERSION[2], int):
str_version = "%s.%s.%s" % VERSION[:3]
else:
str_version = "%s.%s_%s" % VERSION[:3]
else:
str_version = "%s.%s" % VERSION[:2]
__version__ = str_version
# -*- coding: utf-8 -*-
#
# Autocomplete feature for admin panel
#
import six
import operator
from functools import update_wrapper
from six.moves import reduce
from typing import Tuple, Dict, Callable # NOQA
from django.apps import apps
from django.http import HttpResponse, HttpResponseNotFound
from django.conf import settings
from django.db import models
from django.db.models.query import QuerySet
from django.utils.encoding import smart_str
from django.utils.translation import ugettext as _
from django.utils.text import get_text_list
from django.contrib import admin
from django_extensions.admin.widgets import ForeignKeySearchInput
class ForeignKeyAutocompleteAdminMixin(object):
"""Admin class for models using the autocomplete feature.
There are two additional fields:
- related_search_fields: defines fields of managed model that
have to be represented by autocomplete input, together with
a list of target model fields that are searched for
input string, e.g.:
related_search_fields = {
'author': ('first_name', 'email'),
}
- related_string_functions: contains optional functions which
take target model instance as only argument and return string
representation. By default __unicode__() method of target
object is used.
And also an optional additional field to set the limit on the
results returned by the autocomplete query. You can set this integer
value in your settings file using FOREIGNKEY_AUTOCOMPLETE_LIMIT or
you can set this per ForeignKeyAutocompleteAdmin basis. If any value
is set the results will not be limited.
"""
related_search_fields = {} # type: Dict[str, Tuple[str]]
related_string_functions = {} # type: Dict[str, Callable]
autocomplete_limit = getattr(settings, 'FOREIGNKEY_AUTOCOMPLETE_LIMIT', None)
def get_urls(self):
from django.conf.urls import url
def wrap(view):
def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)
return [
url(r'foreignkey_autocomplete/$', wrap(self.foreignkey_autocomplete),
name='%s_%s_autocomplete' % (self.model._meta.app_label, self.model._meta.model_name))
] + super(ForeignKeyAutocompleteAdminMixin, self).get_urls()
def foreignkey_autocomplete(self, request):
"""
Searches in the fields of the given related model and returns the
result as a simple string to be used by the jQuery Autocomplete plugin
"""
query = request.GET.get('q', None)
app_label = request.GET.get('app_label', None)
model_name = request.GET.get('model_name', None)
search_fields = request.GET.get('search_fields', None)
object_pk = request.GET.get('object_pk', None)
try:
to_string_function = self.related_string_functions[model_name]
except KeyError:
if six.PY3:
to_string_function = lambda x: x.__str__()
else:
to_string_function = lambda x: x.__unicode__()
if search_fields and app_label and model_name and (query or object_pk):
def construct_search(field_name):
# use different lookup methods depending on the notation
if field_name.startswith('^'):
return "%s__istartswith" % field_name[1:]
elif field_name.startswith('='):
return "%s__iexact" % field_name[1:]
elif field_name.startswith('@'):
return "%s__search" % field_name[1:]
else:
return "%s__icontains" % field_name
model = apps.get_model(app_label, model_name)
queryset = model._default_manager.all()
data = ''
if query:
for bit in query.split():
or_queries = [models.Q(**{construct_search(smart_str(field_name)): smart_str(bit)}) for field_name in search_fields.split(',')]
other_qs = QuerySet(model)
other_qs.query.select_related = queryset.query.select_related
other_qs = other_qs.filter(reduce(operator.or_, or_queries))
queryset = queryset & other_qs
additional_filter = self.get_related_filter(model, request)
if additional_filter:
queryset = queryset.filter(additional_filter)
if self.autocomplete_limit:
queryset = queryset[:self.autocomplete_limit]
data = ''.join([six.u('%s|%s\n') % (to_string_function(f), f.pk) for f in queryset])
elif object_pk:
try:
obj = queryset.get(pk=object_pk)
except Exception: # FIXME: use stricter exception checking
pass
else:
data = to_string_function(obj)
return HttpResponse(data, content_type='text/plain')
return HttpResponseNotFound()
def get_related_filter(self, model, request):
"""Given a model class and current request return an optional Q object
that should be applied as an additional filter for autocomplete query.
If no additional filtering is needed, this method should return
None."""
def get_help_text(self, field_name, model_name):
searchable_fields = self.related_search_fields.get(field_name, None)
if searchable_fields:
help_kwargs = {
'model_name': model_name,
'field_list': get_text_list(searchable_fields, _('and')),
}
return _('Use the left field to do %(model_name)s lookups in the fields %(field_list)s.') % help_kwargs
return ''
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Overrides the default widget for Foreignkey fields if they are
specified in the related_search_fields class attribute.
"""
if isinstance(db_field, models.ForeignKey) and db_field.name in self.related_search_fields:
help_text = self.get_help_text(db_field.name, db_field.remote_field.model._meta.object_name)
if kwargs.get('help_text'):
help_text = six.u('%s %s' % (kwargs['help_text'], help_text))
kwargs['widget'] = ForeignKeySearchInput(db_field.remote_field, self.related_search_fields[db_field.name])
kwargs['help_text'] = help_text
return super(ForeignKeyAutocompleteAdminMixin, self).formfield_for_dbfield(db_field, **kwargs)
class ForeignKeyAutocompleteAdmin(ForeignKeyAutocompleteAdminMixin, admin.ModelAdmin):
pass
class ForeignKeyAutocompleteTabularInline(ForeignKeyAutocompleteAdminMixin, admin.TabularInline):
pass
class ForeignKeyAutocompleteStackedInline(ForeignKeyAutocompleteAdminMixin, admin.StackedInline):
pass
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.admin import FieldListFilter
from django.contrib.admin.utils import prepare_lookup_value
from django.utils.translation import ugettext_lazy as _
class NullFieldListFilter(FieldListFilter):
def __init__(self, field, request, params, model, model_admin, field_path):
self.lookup_kwarg = '{0}__isnull'.format(field_path)
super(NullFieldListFilter, self).__init__(field, request, params, model, model_admin, field_path)
lookup_choices = self.lookups(request, model_admin)
self.lookup_choices = () if lookup_choices is None else list(lookup_choices)
def expected_parameters(self):
return [self.lookup_kwarg]
def value(self):
return self.used_parameters.get(self.lookup_kwarg, None)
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def choices(self, cl):
yield {
'selected': self.value() is None,
'query_string': cl.get_query_string({}, [self.lookup_kwarg]),
'display': _('All'),
}
for lookup, title in self.lookup_choices:
yield {
'selected': self.value() == prepare_lookup_value(self.lookup_kwarg, lookup),
'query_string': cl.get_query_string({
self.lookup_kwarg: lookup,
}, []),
'display': title,
}
def queryset(self, request, queryset):
if self.value() is not None:
kwargs = {self.lookup_kwarg: self.value()}
return queryset.filter(**kwargs)
return queryset
class NotNullFieldListFilter(NullFieldListFilter):
def lookups(self, request, model_admin):
return (
('0', _('Yes')),
('1', _('No')),
)
# -*- coding: utf-8 -*-
import six
from six.moves import urllib
from django import forms
from django.contrib.admin.sites import site
from django.contrib.admin.widgets import ForeignKeyRawIdWidget
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.utils.text import Truncator
class ForeignKeySearchInput(ForeignKeyRawIdWidget):
"""
A Widget for displaying ForeignKeys in an autocomplete search input
instead in a <select> box.
"""
# Set in subclass to render the widget with a different template
widget_template = None
# Set this to the patch of the search view
search_path = None
def _media(self):
js_files = ['django_extensions/js/jquery.bgiframe.js',
'django_extensions/js/jquery.ajaxQueue.js',
'django_extensions/js/jquery.autocomplete.js']
return forms.Media(css={'all': ('django_extensions/css/jquery.autocomplete.css',)},
js=js_files)
media = property(_media)
def label_for_value(self, value):
key = self.rel.get_related_field().name
obj = self.rel.model._default_manager.get(**{key: value})
return Truncator(obj).words(14, truncate='...')
def __init__(self, rel, search_fields, attrs=None):
self.search_fields = search_fields
super(ForeignKeySearchInput, self).__init__(rel, site, attrs)
def render(self, name, value, attrs=None):
if attrs is None:
attrs = {}
opts = self.rel.model._meta
app_label = opts.app_label
model_name = opts.object_name.lower()
related_url = reverse('admin:%s_%s_changelist' % (app_label, model_name))
if not self.search_path:
self.search_path = urllib.parse.urljoin(related_url, 'foreignkey_autocomplete/')
params = self.url_parameters()
if params:
url = '?' + '&amp;'.join(['%s=%s' % (k, v) for k, v in params.items()])
else:
url = ''
if 'class' not in attrs:
attrs['class'] = 'vForeignKeyRawIdAdminField'
# Call the TextInput render method directly to have more control
output = [forms.TextInput.render(self, name, value, attrs)]
if value:
label = self.label_for_value(value)
else:
label = six.u('')
context = {
'url': url,
'related_url': related_url,
'search_path': self.search_path,
'search_fields': ','.join(self.search_fields),