Skip to content

Commit

Permalink
Attempt to maintain the empty choice in the form fields
Browse files Browse the repository at this point in the history
  • Loading branch information
ralphje committed Dec 1, 2014
1 parent a363e7e commit 761fef3
Show file tree
Hide file tree
Showing 5 changed files with 129 additions and 8 deletions.
1 change: 1 addition & 0 deletions internationalflavor/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = '0.1'
9 changes: 7 additions & 2 deletions internationalflavor/countries/forms.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django import forms
from .data import UN_RECOGNIZED_COUNTRIES, get_countries_sorted_lazy
from .data import UN_RECOGNIZED_COUNTRIES, get_countries_sorted_lazy, get_countries_sorted


class CountryFormField(forms.TypedChoiceField):
Expand All @@ -9,5 +9,10 @@ class CountryFormField(forms.TypedChoiceField):
"""

def __init__(self, countries=UN_RECOGNIZED_COUNTRIES, exclude=(), *args, **kwargs):
kwargs['choices'] = get_countries_sorted_lazy(countries, exclude)
# Maintain the empty choice if available
if kwargs['choices'] and kwargs['choices'][0][0] == '':
kwargs['choices'] = [kwargs['choices'][0]] + get_countries_sorted(countries, exclude)
else:
kwargs['choices'] = get_countries_sorted_lazy(countries, exclude)

super(CountryFormField, self).__init__(*args, **kwargs)
9 changes: 8 additions & 1 deletion internationalflavor/timezone/data.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from django.utils import six
from django.utils.encoding import force_text
from django.utils.functional import lazy
import itertools
from _cldr_data import METAZONE_NAMES, TIMEZONE_NAMES, METAZONE_MAPPING
Expand All @@ -23,10 +25,15 @@ def get_timezones_cities_sorted(timezones=COMMON_TIMEZONES, exclude=()):
return result


def _format_tz_name(*strings):
return ', '.join(force_text(s) for s in strings[::-1])
format_tz_name = lazy(_format_tz_name, six.text_type)


def get_timezones_cities(timezones=COMMON_TIMEZONES, exclude=()):
"""Same as get_timezones_cities_sorted, but does not sort or group the values."""

return [(k, ', '.join(v[::-1])) for k, v in TIMEZONE_NAMES.items() if k in timezones and k not in exclude]
return [(k, format_tz_name(*v)) for k, v in TIMEZONE_NAMES.items() if k in timezones and k not in exclude]


get_timezones_cities_sorted_lazy = lazy(get_timezones_cities_sorted, list)
Expand Down
9 changes: 7 additions & 2 deletions internationalflavor/timezone/forms.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
from django import forms
from .data import COMMON_TIMEZONES, get_timezones_cities_sorted_lazy
from .data import COMMON_TIMEZONES, get_timezones_cities_sorted_lazy, get_timezones_cities_sorted


class TimezoneFormField(forms.TypedChoiceField):
def __init__(self, timezones=None, exclude=(), *args, **kwargs):
if timezones is None:
timezones = COMMON_TIMEZONES

kwargs['choices'] = get_timezones_cities_sorted_lazy(timezones, exclude)
# Maintain the empty choice if available
if kwargs['choices'] and kwargs['choices'][0][0] == '':
kwargs['choices'] = [kwargs['choices'][0]] + get_timezones_cities_sorted(timezones, exclude)
else:
kwargs['choices'] = get_timezones_cities_sorted_lazy(timezones, exclude)

super(TimezoneFormField, self).__init__(*args, **kwargs)
109 changes: 106 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,112 @@
from distutils.core import setup
import os
import re
import sys
import codecs
from fnmatch import fnmatchcase
from distutils.util import convert_path
from setuptools import setup, find_packages


def read(*parts):
filename = os.path.join(os.path.dirname(__file__), *parts)
with codecs.open(filename, encoding='utf-8') as fp:
return fp.read()


def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")


# Provided as an attribute, so you can append to these instead
# of replicating them:
standard_exclude = ('*.py', '*.pyc', '*$py.class', '*~', '.*', '*.bak')
standard_exclude_directories = ('.*', 'CVS', '_darcs', './build',
'./dist', 'EGG-INFO', '*.egg-info')


# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
# Note: you may want to copy this into your setup.py file verbatim, as
# you can't import this from another package, when you don't know if
# that package is installed yet.
def find_package_data(where='.', package='',
exclude=standard_exclude,
exclude_directories=standard_exclude_directories,
only_in_packages=True,
show_ignored=False):
"""
Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary looks like::
{'package': [files]}
Where ``files`` is a list of all the files in that package that
don't match anything in ``exclude``.
If ``only_in_packages`` is true, then top-level directories that
are not packages won't be included (but directories under packages
will).
Directories matching any pattern in ``exclude_directories`` will
be ignored; by default directories with leading ``.``, ``CVS``,
and ``_darcs`` will be ignored.
If ``show_ignored`` is true, then all the files that aren't
included in package data are shown on stderr (for debugging
purposes).
Note patterns use wildcards, or can be exact paths (including
leading ``./``), and all searching is case-insensitive.
"""

out = {}
stack = [(convert_path(where), '', package, only_in_packages)]
while stack:
where, prefix, package, only_in_packages = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where, name)
if os.path.isdir(fn):
bad_name = False
for pattern in exclude_directories:
if (fnmatchcase(name, pattern) or fn.lower() == pattern.lower()):
bad_name = True
if show_ignored:
print >> sys.stderr, (
"Directory %s ignored by pattern %s"
% (fn, pattern))
break
if bad_name:
continue
if (os.path.isfile(os.path.join(fn, '__init__.py')) and not prefix):
if not package:
new_package = name
else:
new_package = package + '.' + name
stack.append((fn, '', new_package, False))
else:
stack.append((fn, prefix + name + '/', package, only_in_packages))
elif package or not only_in_packages:
# is a file
bad_name = False
for pattern in exclude:
if (fnmatchcase(name, pattern) or fn.lower() == pattern.lower()):
bad_name = True
if show_ignored:
print >> sys.stderr, (
"File %s ignored by pattern %s"
% (fn, pattern))
break
if bad_name:
continue
out.setdefault(package, []).append(prefix + name)
return out


setup(
name='django-internationalflavor',
version='0.1',
packages=['internationalflavor'],
version=find_version("internationalflavor", "__init__.py"),
packages=find_packages(exclude=['tests', 'tests.*']),
package_data=find_package_data(),
url='https://github.com/ralphje/django-internationalflavor',
license='MIT',
author='Ralph Broenink',
Expand Down

0 comments on commit 761fef3

Please sign in to comment.