Added six types and fixed setup

This commit is contained in:
Johannes Hoppe 2015-03-30 11:19:27 +02:00
parent 2cfbfd3325
commit bd40acc761
10 changed files with 76 additions and 85 deletions

View file

@ -20,6 +20,8 @@ matrix:
exclude:
- python: "3.2"
env: DJANGO="<1.5,>=1.4"
- python: "3.2"
env: DJANGO="<1.8,>=1.7"
- python: "3.3"
env: DJANGO="<1.5,>=1.4"
- python: "3.4"
@ -30,13 +32,9 @@ matrix:
env: DJANGO="<1.8,>=1.7"
allow_failures:
- env: DJANGO="==1.8rc1"
- python: "3.2"
- python: "3.3"
- python: "3.4"
- python: "pypy3"
install:
- pip install --upgrade pip
- pip install .
- pip install -e .
- pip install -r requirements_dev.txt
- pip install Django$DJANGO
- pip install coveralls

View file

@ -12,7 +12,7 @@ from django.core import validators
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.forms.models import ModelChoiceIterator
from django.utils.encoding import force_unicode, smart_unicode
from django.utils.encoding import force_text, smart_text
from django.utils.translation import ugettext_lazy as _
from . import util
@ -57,7 +57,7 @@ class AutoViewFieldMixin(object):
:type auto_id: :py:obj:`unicode`
"""
name = kwargs.pop('auto_id', u"%s.%s" % (self.__module__, self.__class__.__name__))
name = kwargs.pop('auto_id', "%s.%s" % (self.__module__, self.__class__.__name__))
if logger.isEnabledFor(logging.INFO):
logger.info("Registering auto field: %s", name)
@ -170,7 +170,7 @@ class ModelResultJsonMixin(object):
:return: The label string.
:rtype: :py:obj:`unicode`
"""
return smart_unicode(obj)
return smart_text(obj)
def extra_data_from_instance(self, obj):
"""
@ -519,9 +519,9 @@ class HeavyChoiceField(ChoiceMixin, forms.Field):
to be a subset of all possible choices.
"""
default_error_messages = {
'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
}
empty_value = u''
empty_value = ''
"Sub-classes can set this other value if needed."
def __init__(self, *args, **kwargs):
@ -544,9 +544,9 @@ class HeavyChoiceField(ChoiceMixin, forms.Field):
raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
def valid_value(self, value):
uvalue = smart_unicode(value)
uvalue = smart_text(value)
for k, v in self.choices:
if uvalue == smart_unicode(k):
if uvalue == smart_text(k):
return True
return self.validate_value(value)
@ -556,7 +556,7 @@ class HeavyChoiceField(ChoiceMixin, forms.Field):
Sub-classes should override this if they do not want Unicode values.
"""
return smart_unicode(value)
return smart_text(value)
def validate_value(self, value):
"""
@ -602,8 +602,8 @@ class HeavyMultipleChoiceField(HeavyChoiceField):
"""
hidden_widget = forms.MultipleHiddenInput
default_error_messages = {
'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
'invalid_list': _(u'Enter a list of values.'),
'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
'invalid_list': _('Enter a list of values.'),
}
def to_python(self, value):
@ -729,7 +729,7 @@ class HeavyModelSelect2TagField(HeavySelect2FieldBaseMixin, ModelMultipleChoiceF
new_values.append(pk)
for val in new_values:
value.append(self.create_new_value(force_unicode(val)))
value.append(self.create_new_value(force_text(val)))
# Usually new_values will have list of new tags, but if the tag is
# suppose of type int then that could be interpreted as valid pk
@ -737,9 +737,9 @@ class HeavyModelSelect2TagField(HeavySelect2FieldBaseMixin, ModelMultipleChoiceF
# Below we find such tags and create them, by check if the pk
# actually exists.
qs = self.queryset.filter(**{'%s__in' % key: value})
pks = set([force_unicode(getattr(o, key)) for o in qs])
pks = set([force_text(getattr(o, key)) for o in qs])
for i in range(0, len(value)):
val = force_unicode(value[i])
val = force_text(value[i])
if val not in pks:
value[i] = self.create_new_value(val)
# Since this overrides the inherited ModelChoiceField.clean
@ -861,8 +861,8 @@ class AutoModelSelect2TagField(ModelResultJsonMixin, AutoViewFieldMixin, HeavyMo
class Tag(models.Model):
tag = models.CharField(max_length=10, unique=True)
def __unicode__(self):
return unicode(self.tag)
def __str__(self):
return text_type(self.tag)
class TagField(AutoModelSelect2TagField):
queryset = Tag.objects

View file

@ -1,6 +1,8 @@
# -*- coding:utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.utils.six import binary_type
import memcache
@ -29,6 +31,6 @@ class Client(object):
return self.server.get(self.normalize_key(key))
def normalize_key(self, key):
key = str(key)
key = binary_type(key)
key = key.replace(' ', '-')
return key

View file

@ -2,6 +2,7 @@
from __future__ import absolute_import, unicode_literals
from django import template
from django_select2.widgets import HeavySelect2Widget, Select2Widget
register = template.Library()
@ -13,17 +14,17 @@ __proxy_light_widget = Select2Widget()
@register.simple_tag(name='import_django_select2_js')
def import_js(light=0):
if light:
return u'\n'.join(__proxy_light_widget.media.render_js())
return '\n'.join(__proxy_light_widget.media.render_js())
else:
return u'\n'.join(__proxy_widget.media.render_js())
return '\n'.join(__proxy_widget.media.render_js())
@register.simple_tag(name='import_django_select2_css')
def import_css(light=0):
if light:
return u'\n'.join(__proxy_light_widget.media.render_css())
return '\n'.join(__proxy_light_widget.media.render_css())
else:
return u'\n'.join(__proxy_widget.media.render_css())
return '\n'.join(__proxy_widget.media.render_css())
@register.simple_tag(name='import_django_select2_js_css')

View file

@ -7,6 +7,8 @@ import logging
import re
import threading
from django.utils.six import binary_type, text_type
from . import __ENABLE_MULTI_PROCESS_SUPPORT as ENABLE_MULTI_PROCESS_SUPPORT
from . import __GENERATE_RANDOM_ID as GENERATE_RANDOM_ID
from . import __MEMCACHE_HOST as MEMCACHE_HOST
@ -78,7 +80,7 @@ def is_valid_id(val):
if ENABLE_MULTI_PROCESS_SUPPORT:
from memcache_wrapped_db_client import Client
remote_server = Client(MEMCACHE_HOST, str(MEMCACHE_PORT), MEMCACHE_TTL)
remote_server = Client(MEMCACHE_HOST, binary_type(MEMCACHE_PORT), MEMCACHE_TTL)
@synchronized
@ -106,9 +108,9 @@ def register_field(key, field):
if key not in __field_store:
# Generating id
if GENERATE_RANDOM_ID:
id_ = u"%d:%s" % (len(__id_store), unicode(datetime.datetime.now()))
id_ = "%d:%s" % (len(__id_store), text_type(datetime.datetime.now()))
else:
id_ = unicode(hashlib.sha1("%s:%s" % (key, SECRET_SALT)).hexdigest())
id_ = text_type(hashlib.sha1(":".join((key, SECRET_SALT)).encode('utf-8')).hexdigest())
__field_store[key] = id_
__id_store[id_] = field

View file

@ -5,6 +5,7 @@ import json
from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpResponse
from django.utils.six import binary_type
from django.views.generic import View
from .util import get_field, is_valid_id
@ -51,7 +52,7 @@ class Select2View(JSONResponseMixin, View):
def dispatch(self, request, *args, **kwargs):
try:
self.check_all_permissions(request, *args, **kwargs)
except Exception, e:
except Exception as e:
return self.respond_with_exception(e)
return super(Select2View, self).dispatch(request, *args, **kwargs)
@ -92,7 +93,7 @@ class Select2View(JSONResponseMixin, View):
else:
status = getattr(e, 'status_code', 400)
return self.render_to_response(
self._results_to_context((str(e), False, [],)),
self._results_to_context((binary_type(e), False, [],)),
status=status
)

View file

@ -13,7 +13,7 @@ from django import forms
from django.core.urlresolvers import reverse
from django.core.validators import EMPTY_VALUES
from django.utils.datastructures import MergeDict, MultiValueDict
from django.utils.encoding import force_unicode
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.six import text_type
@ -194,7 +194,7 @@ class Select2Mixin(object):
"""
if id_:
return self.render_js_script(self.render_inner_js_code(id_, *args))
return u''
return ''
def render_js_script(self, inner_code):
"""
@ -208,7 +208,7 @@ class Select2Mixin(object):
:rtype: :py:obj:`unicode`
"""
return u"""
return """
<script type="text/javascript">
jQuery(function ($) {
%s
@ -226,7 +226,7 @@ class Select2Mixin(object):
options = json.dumps(self.get_options())
options = options.replace('"*START*', '').replace('*END*"', '')
# selector variable must already be passed to this
return u'$(hashedSelector).select2(%s);' % (options)
return '$(hashedSelector).select2(%s);' % (options)
def render(self, name, value, attrs=None, choices=()):
"""
@ -315,13 +315,13 @@ class MultipleSelect2HiddenInput(forms.TextInput):
def render(self, name, value, attrs=None, choices=()):
attrs = self.build_attrs(attrs, multiple='multiple')
s = unicode(super(MultipleSelect2HiddenInput, self).render(name, u"", attrs))
s = text_type(super(MultipleSelect2HiddenInput, self).render(name, "", attrs))
id_ = attrs.get('id', None)
if id_:
jscode = u''
jscode = ''
if value:
jscode = u'$("#%s").val(django_select2.convertArrToStr(%s));' % (id_, json.dumps(value))
jscode += u"django_select2.initMultipleHidden($('#%s'));" % id_
jscode = '$("#%s").val(django_select2.convertArrToStr(%s));' % (id_, json.dumps(value))
jscode += "django_select2.initMultipleHidden($('#%s'));" % id_
s += self.render_js_script(jscode)
return mark_safe(s)
@ -337,8 +337,8 @@ class MultipleSelect2HiddenInput(forms.TextInput):
data = []
if len(initial) != len(data):
return True
initial_set = set([force_unicode(value) for value in initial])
data_set = set([force_unicode(value) for value in data])
initial_set = set([force_text(value) for value in initial])
data_set = set([force_text(value) for value in data])
return data_set != initial_set
@ -409,7 +409,7 @@ class HeavySelect2Mixin(Select2Mixin):
self.options = dict(self.options) # Making an instance specific copy
self.view = kwargs.pop('data_view', None)
self.url = kwargs.pop('data_url', None)
self.userGetValTextFuncName = kwargs.pop('userGetValTextFuncName', u'null')
self.userGetValTextFuncName = kwargs.pop('userGetValTextFuncName', 'null')
self.choices = kwargs.pop('choices', [])
if not self.view and not self.url:
@ -439,18 +439,18 @@ class HeavySelect2Mixin(Select2Mixin):
:return: The rendered JS array code.
:rtype: :py:obj:`unicode`
"""
selected_choices = list(force_unicode(v) for v in selected_choices)
selected_choices = list(force_text(v) for v in selected_choices)
txts = []
all_choices = choices if choices else []
choices_dict = dict()
self_choices = self.choices
import fields
from . import fields
if isinstance(self_choices, fields.FilterableModelChoiceIterator):
self_choices.set_extra_filter(**{'%s__in' % self.field.get_pk_field_name(): selected_choices})
for val, txt in chain(self_choices, all_choices):
val = force_unicode(val)
val = force_text(val)
choices_dict[val] = txt
for val in selected_choices:
@ -501,10 +501,10 @@ class HeavySelect2Mixin(Select2Mixin):
values = [value]
texts = self.render_texts(values, choices)
if texts:
return u"$('#%s').txt(%s);" % (id_, texts)
return "$('#%s').txt(%s);" % (id_, texts)
def render_inner_js_code(self, id_, name, value, attrs=None, choices=(), *args):
js = u'$(hashedSelector).change(django_select2.onValChange).data("userGetValText", null);'
js = '$(hashedSelector).change(django_select2.onValChange).data("userGetValText", null);'
texts = self.render_texts_for_value(id_, value, choices)
if texts:
js += texts
@ -574,7 +574,7 @@ class HeavySelect2MultipleWidget(HeavySelect2Mixin, MultipleSelect2HiddenInput):
if value:
texts = self.render_texts(value, choices)
if texts:
return u'$("#%s").txt(%s);' % (id_, texts)
return '$("#%s").txt(%s);' % (id_, texts)
class HeavySelect2TagWidget(HeavySelect2MultipleWidget):
@ -611,7 +611,7 @@ class HeavySelect2TagWidget(HeavySelect2MultipleWidget):
if '__prefix__' in id_:
return ''
else:
js = u'''
js = '''
window.django_select2.%s = function (selector, fieldID) {
var hashedSelector = "#" + selector;
$(hashedSelector).data("field_id", fieldID);
@ -654,7 +654,7 @@ class AutoHeavySelect2Mixin(object):
if '__prefix__' in id_:
return ''
else:
js = u'''
js = '''
window.django_select2.%s = function (selector, fieldID) {
var hashedSelector = "#" + selector;
$(hashedSelector).data("field_id", fieldID);

View file

@ -3,6 +3,7 @@ norecursedirs=env testapp docs
addopts = --tb=short --pep8 --flakes -rxs
pep8maxlinelength=139
pep8ignore=
runtests.py ALL
flakes-ignore=
django_select2/__init__.py UnusedImport
django_select2/fields.py UnusedImport

View file

@ -4,4 +4,5 @@ pytest-flakes
pytest-django
selenium
model_mommy
isort
isort
requests

View file

@ -9,9 +9,9 @@ import sys
from setuptools import setup, find_packages, Command
def read(fname):
f = codecs.open(os.path.join(os.path.dirname(__file__), fname), 'rb')
return f.read()
def read(file_name):
file_path = os.path.join(os.path.dirname(__file__), file_name)
return codecs.open(file_path, encoding='utf-8').read()
PACKAGE = "django_select2"
@ -28,42 +28,27 @@ def getPkgPath():
def minify(files, outfile, ftype):
import urllib
import json
import requests
import io
content = ''
content = u''
for filename in files:
with open(getPkgPath() + filename) as f:
for line in f.xreadlines():
if isinstance(line, str):
line = line.decode('utf-8')
content = content + line
with io.open(getPkgPath() + filename, 'rb', encoding='utf8') as f:
content = f.read()
data = urllib.urlencode([
('code', content.encode('utf-8')),
('type', ftype),
])
f = urllib.urlopen('http://api.applegrew.com/minify', data)
data = u''
while 1:
line = f.readline()
if line:
if isinstance(line, str):
line = line.decode('utf-8')
data = data + line
else:
break
f.close()
data = json.loads(data)
if data['success']:
with open(getPkgPath() + outfile, 'w') as f:
f.write(data['compiled_code'].encode('utf8'))
data = {
'code': content,
'type': ftype,
}
response = requests.post('http://api.applegrew.com/minify', data)
response.raise_for_status()
response = response.json()
if response['success']:
with io.open(getPkgPath() + outfile, 'w', encoding='utf8') as f:
f.write(response['compiled_code'])
else:
print data['error_code']
print data['error']
raise Exception('Could not minify.')
raise Exception('%(error_code)s: "%(error)s"' % response)
if len(sys.argv) > 1 and 'sdist' == sys.argv[1]: