Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deprecation warnings #1

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,29 @@ Dependencies
============

django-countries (http://pypi.python.org/pypi/django-countries)
django-localflavor (http://pypi.python.org/pypi/django-localflavor)

Usage
=====

1. Add django-countries and django-postal to your ``INSTALLED_APPS`` in ``settings.py``
1. Add django-countries, django-localflavor and django-postal to your ``INSTALLED_APPS`` in ``settings.py``
e.g.::

INSTALLED_APPS = (
"countries",
"django_countries",
"localflavor",
"postal",
...
)

2. Include the postal urls in your main ``urls.py`` file::

urlpatterns = [
# ...
url(r'^postal/', include('postal.urls')),
# ...
]

3. Add a ``postal_form`` to your templates::

some_template.html
Expand All @@ -77,7 +87,7 @@ e.g.::

Changing the country in the form above should localise the address form.

3. In your view code add code to save the addressform e.g.::
4. In your view code add code to save the addressform e.g.::

from postal.forms import PostalAddressForm

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def read(fname):
package_dir={'': 'src'},
package_data={'': ['*.txt', '*.js', '*.html', '*.*', 'templates/postal/*.html']},

install_requires=['setuptools', 'django-countries'],
install_requires=['setuptools', 'django-countries', 'django-localflavor'],

classifiers=[
'Development Status :: 3 - Alpha',
Expand Down
4 changes: 2 additions & 2 deletions src/postal/api/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
class PostalHandler(BaseHandler):
allowed_methods = ('GET',)

def read(self, request):
def read(self, request):
iso_code = request.GET.get('country', '')
json = {}
form_class = form_factory(country_code=iso_code)
form_obj = form_class()
for k, v in form_obj.fields.items():
if k not in json.keys():
json[k] = {}
json[k]['label'] = unicode(v.label)
json[k]['label'] = str(v.label)
json[k]['widget'] = v.widget.render(k, "", attrs={'id': 'id_' + k})
return json
51 changes: 49 additions & 2 deletions src/postal/forms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,30 @@
from django.utils.translation import ugettext_lazy as _
from django_countries import data as country_data


from postal.settings import POSTAL_ADDRESS_LINE1, POSTAL_ADDRESS_LINE2, POSTAL_ADDRESS_CITY, POSTAL_ADDRESS_STATE, \
POSTAL_ADDRESS_CODE
POSTAL_ADDRESS_CODE, POSTAL_USE_CRISPY_FORMS

if POSTAL_USE_CRISPY_FORMS:
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Hidden


def country_sort_key(country_data):
if country_data[0] == 'US':
return 'AAA'
if country_data[0] == 'CA':
return 'AAAA'
return country_data[1]


country_list = [('', '-'*45)] + country_data.COUNTRIES.items()
country_list = sorted([('', '-' * 45)] + list(country_data.COUNTRIES.items()), key=country_sort_key)

form_helpers = {}


def register_postal_form_helper(form_id, form_helper):
form_helpers[form_id] = form_helper


class PostalAddressForm(forms.Form):
Expand All @@ -16,6 +36,33 @@ class PostalAddressForm(forms.Form):
code = forms.CharField(label=POSTAL_ADDRESS_CODE[0], required=POSTAL_ADDRESS_CODE[1], max_length=100)
country = forms.ChoiceField(label=_(u"Country"), choices=country_list)

def __init__(self, *args, **kwargs):
prefix = kwargs.pop('prefix', None)
postal_form_id = kwargs.pop('postal_form_id', 'postal-address-form')
if POSTAL_USE_CRISPY_FORMS:
css_id = 'postal_address'
if prefix is not None:
css_id = prefix + '-' + css_id
if postal_form_id in form_helpers:
self.helper = form_helpers[postal_form_id]
else:
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
Div(
'country',
'line1',
'line2',
'city',
'state',
'code',
css_id=css_id,
css_class='postal_address'
),
Hidden('postal-form-id', postal_form_id),
)
super(PostalAddressForm, self).__init__(*args, **kwargs)

def clean_country(self):
data = self.cleaned_data['country']
if data not in country_data.COUNTRIES.keys():
Expand Down
Empty file added src/postal/forms/au/__init__.py
Empty file.
17 changes: 17 additions & 0 deletions src/postal/forms/au/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
""" http://www.bitboost.com/ref/international-address-formats.html """
from django import forms
from django.utils.translation import ugettext_lazy as _
from localflavor.au.forms import AUPostCodeField, AUStateSelect

from postal.forms import PostalAddressForm

class AUPostalAddressForm(PostalAddressForm):
line1 = forms.CharField(label=_(u"Street"), max_length=50)
line2 = forms.CharField(label=_(u"Street (con\'t)"), required=False, max_length=100)
city = forms.CharField(label=_(u"City"), max_length=50)
state = forms.CharField(label=_(u"US State"), widget=AUStateSelect)
code = AUPostCodeField(label=_(u"Zip Code"))

def __init__(self, *args, **kwargs):
super(AUPostalAddressForm, self).__init__(*args, **kwargs)
self.fields['country'].initial = "AU"
Empty file added src/postal/forms/ca/__init__.py
Empty file.
18 changes: 18 additions & 0 deletions src/postal/forms/ca/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
""" http://www.bitboost.com/ref/international-address-formats.html """
from django import forms
from django.utils.translation import ugettext_lazy as _
from localflavor.ca.forms import CAPostalCodeField, CAProvinceField, CAProvinceSelect

from postal.forms import PostalAddressForm


class CAPostalAddressForm(PostalAddressForm):
line1 = forms.CharField(label=_(u"Street Address"), max_length=50)
line2 = forms.CharField(label=_(u"Street Address (con\'t)"), required=False, max_length=100)
city = forms.CharField(label=_(u"City"), max_length=50)
state = CAProvinceField(label=_(u"Province"), widget=CAProvinceSelect)
code = CAPostalCodeField(label=_(u"Postal Code"))

def __init__(self, *args, **kwargs):
super(CAPostalAddressForm, self).__init__(*args, **kwargs)
self.fields['country'].initial = "CA"
17 changes: 14 additions & 3 deletions src/postal/forms/nl/forms.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.utils import six
from localflavor.nl.forms import NLZipCodeField

from postal.forms import PostalAddressForm

class MyNLZipCodeField(NLZipCodeField):
def clean(self, value):
if isinstance(value, six.string_types):
value = value.upper().replace(' ', '')

# don't strip the spaces out of the zipcode, it confuses
# the geocoders
return super(NLZipCodeField, self).clean(value)


class NLPostalAddressForm(PostalAddressForm):
line1 = forms.CharField(label=_(u"Street"), required=False, max_length=100)
line1 = forms.CharField(label=_(u"Street"), max_length=100)
line2 = forms.CharField(label=_(u"Area"), required=False, max_length=100)
city = forms.CharField(label=_(u"Town/City"), required=False, max_length=100)
code = NLZipCodeField(label=_(u"Zip Code"))
city = forms.CharField(label=_(u"Town/City"), max_length=100)
code = MyNLZipCodeField(label=_(u"Zip Code"))


class Meta:
Expand Down
4 changes: 2 additions & 2 deletions src/postal/forms/us/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from postal.forms import PostalAddressForm

class USPostalAddressForm(PostalAddressForm):
line1 = forms.CharField(label=_(u"Street"), max_length=50)
line2 = forms.CharField(label=_(u"Area"), required=False, max_length=100)
line1 = forms.CharField(label=_(u"Street Address"), max_length=50)
line2 = forms.CharField(label=_(u"Street Address (con\'t)"), required=False, max_length=100)
city = forms.CharField(label=_(u"City"), max_length=50)
state = USStateField(label=_(u"US State"), widget=USStateSelect)
code = USZipCodeField(label=_(u"Zip Code"))
Expand Down
5 changes: 4 additions & 1 deletion src/postal/library.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from django import forms
from postal import settings as postal_settings
from postal.forms import PostalAddressForm
from postal.forms.ar.forms import ARPostalAddressForm
Expand All @@ -13,9 +12,12 @@
from postal.forms.pl.forms import PLPostalAddressForm
from postal.forms.ru.forms import RUPostalAddressForm
from postal.forms.us.forms import USPostalAddressForm
from postal.forms.ca.forms import CAPostalAddressForm
from postal.forms.au.forms import AUPostalAddressForm

# TODO: Auto-import these forms
country_map = {
"ca": CAPostalAddressForm,
"co": COPostalAddressForm,
"cz": CZPostalAddressForm,
"de": DEPostalAddressForm,
Expand All @@ -28,6 +30,7 @@
"ru": RUPostalAddressForm,
"us": USPostalAddressForm,
"ar": ARPostalAddressForm,
"au": AUPostalAddressForm,
}


Expand Down
34 changes: 18 additions & 16 deletions src/postal/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
import inspect
import re
import sys
from django.core.urlresolvers import NoReverseMatch
from django.db.models import Model, permalink
from django.urls import NoReverseMatch, reverse
from django.db.models import Model
from django.http import HttpResponse, HttpResponseNotAllowed, HttpResponseServerError
from django.utils.encoding import smart_unicode
from django.utils.encoding import smart_text
from django.views.debug import ExceptionReporter
from django.views.decorators.vary import vary_on_headers
from django.conf import settings
Expand Down Expand Up @@ -66,7 +66,7 @@ def construct(self):
"""
Recursively serialize a lot of types, and
in cases where it doesn't recognize the type,
it will fall back to Django's `smart_unicode`.
it will fall back to Django's `smart_text`.

Returns `dict`.
"""
Expand Down Expand Up @@ -98,7 +98,7 @@ def _any(thing, fields=None):
elif repr(thing).startswith("<django.db.models.fields.related.RelatedManager"):
ret = _any(thing.all())
else:
ret = smart_unicode(thing, strings_only=True)
ret = smart_text(thing, strings_only=True)

return ret

Expand Down Expand Up @@ -238,8 +238,8 @@ def _model(data, fields=None):
url_id, fields = handler.resource_uri(data)

try:
ret['resource_uri'] = permalink(lambda: (url_id, fields))()
except NoReverseMatch, e:
ret['resource_uri'] = reverse(url_id, args=fields)
except NoReverseMatch as e:
pass

if hasattr(data, 'get_api_url') and 'resource_uri' not in ret:
Expand Down Expand Up @@ -304,7 +304,7 @@ def get(cls, format):
"""
Gets an emitter, returns the class and a content-type.
"""
if cls.EMITTERS.has_key(format):
if format in cls.EMITTERS:
return cls.EMITTERS.get(format)

raise ValueError("No emitters found for type %s" % format)
Expand Down Expand Up @@ -409,7 +409,7 @@ class Resource(object):

def __init__(self, handler, authentication=None):
if not callable(handler):
raise AttributeError, "Handler not callable."
raise AttributeError("Handler not callable.")

self.handler = handler()
self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True)
Expand Down Expand Up @@ -540,7 +540,7 @@ def __call__(self, request, *args, **kwargs):

try:
result = meth(request, *args, **kwargs)
except Exception, e:
except Exception as e:
result = self.error_handler(e, request, meth, em_format)

try:
Expand All @@ -557,15 +557,15 @@ def __call__(self, request, *args, **kwargs):
status_code = 200

# If we're looking at a response object which contains non-string
# content, then assume we should use the emitter to format that
# content, then assume we should use the emitter to format that
# content
if isinstance(result, HttpResponse) and not result._is_string:
status_code = result.status_code
# Note: We can't use result.content here because that method attempts
# to convert the content into a string which we don't want.
# to convert the content into a string which we don't want.
# when _is_string is False _container is the raw data
result = result._container

srl = emitter(result, typemapper, handler, fields, anonymous)

try:
Expand All @@ -575,8 +575,10 @@ def __call__(self, request, *args, **kwargs):
before sending it to the client. Won't matter for
smaller datasets, but larger will have an impact.
"""
if self.stream: stream = srl.stream_render(request)
else: stream = srl.render(request)
if self.stream:
stream = srl.stream_render(request)
else:
stream = srl.render(request)

if not isinstance(stream, HttpResponse):
resp = HttpResponse(stream, mimetype=ct, status=status_code)
Expand All @@ -586,7 +588,7 @@ def __call__(self, request, *args, **kwargs):
resp.streaming = self.stream

return resp
except HttpStatusCode, e:
except HttpStatusCode as e:
return e.response

@staticmethod
Expand Down
4 changes: 3 additions & 1 deletion src/postal/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
from django.utils.translation import ugettext_lazy as _

POSTAL_ADDRESS_L10N = getattr(settings, 'POSTAL_ADDRESS_L10N', True)
POSTAL_USE_CRISPY_FORMS = getattr(settings, 'POSTAL_USE_CRISPY_FORMS', False)

# each address line is a tuple of format (field_label, required)
POSTAL_ADDRESS_LINE1 = getattr(settings, "POSTAL_ADDRESS_LINE1", (_(u"Street"), False))
POSTAL_ADDRESS_LINE2 = getattr(settings, "POSTAL_ADDRESS_LINE2", (_(u"Area"), False))
POSTAL_ADDRESS_CITY = getattr(settings, "POSTAL_ADDRESS_CITY", (_(u"City"), False))
POSTAL_ADDRESS_STATE = getattr(settings, "POSTAL_ADDRESS_STATE", (_(u"State"), False))
POSTAL_ADDRESS_CODE = getattr(settings, "POSTAL_ADDRESS_CODE", (_(u"Zip code"), False))
POSTAL_ADDRESS_CODE = getattr(settings, "POSTAL_ADDRESS_CODE", (_(u"Zip code"), False))

2 changes: 2 additions & 0 deletions src/postal/templates/postal/crispyform.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{% load crispy_forms_tags %}
{% crispy form %}
4 changes: 3 additions & 1 deletion src/postal/templates/postal/form.html
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
{{form.as_p}}
<div id="{% if prefix %}{{ prefix }}-{% endif %}postal_address" class="postal_address">
{{form.as_p}}
</div>
Loading