├── humandt
├── models.py
├── __init__.py
├── tests.py
├── parser.py
└── fields.py
├── .gitignore
├── example_project
├── __init__.py
├── dev.db
├── urls.py
├── manage.py
├── templates
│ └── example.html
├── views.py
└── settings.py
├── setup.py
├── README.rst
└── LICENSE
/humandt/models.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 |
3 |
--------------------------------------------------------------------------------
/example_project/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/humandt/__init__.py:
--------------------------------------------------------------------------------
1 | __version__ = '0.2'
2 |
--------------------------------------------------------------------------------
/example_project/dev.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffbr13/django-human-datetime/master/example_project/dev.db
--------------------------------------------------------------------------------
/example_project/urls.py:
--------------------------------------------------------------------------------
1 | from django.conf.urls.defaults import *
2 | from django.contrib import admin
3 | admin.autodiscover()
4 |
5 | urlpatterns = patterns('',
6 | (r'^admin/', include(admin.site.urls)),
7 | ('', 'views.example'),
8 | )
9 |
--------------------------------------------------------------------------------
/example_project/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import os
3 | import sys
4 |
5 | if __name__ == "__main__":
6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
7 |
8 | from django.core.management import execute_from_command_line
9 |
10 | execute_from_command_line(sys.argv)
11 |
--------------------------------------------------------------------------------
/humandt/tests.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | from .parser import parse
3 | from datetime import datetime
4 |
5 | class HumanTests(TestCase):
6 | def setUp(self):
7 | self.now = datetime.now()
8 |
9 | def test_tomorrow(self):
10 | t = parse('tomorrow 4PM')
11 | self.assertEqual(t.day, self.now.day+1)
12 | self.assertEqual(t.hour, 16)
13 |
--------------------------------------------------------------------------------
/humandt/parser.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | from django.core.exceptions import ImproperlyConfigured
3 | from django.conf import settings
4 |
5 | try:
6 | import parsedatetime as pdt
7 | from parsedatetime import Constants
8 | from pytz import timezone
9 | except ImportError:
10 | raise ImproperlyConfigured('Need to install parsedatetime and pytz')
11 |
12 | TZ = timezone(getattr(settings, "TIME_ZONE", "UTC"))
13 |
14 | def parse(s):
15 | """
16 | Parse the string using parsedatetime and format it to the current timezone
17 | """
18 | return TZ.localize(datetime(*tuple(pdt.Calendar(Constants()).parse(s)[0])[:7]))
19 |
--------------------------------------------------------------------------------
/example_project/templates/example.html:
--------------------------------------------------------------------------------
1 |
16 |
17 |
--------------------------------------------------------------------------------
/example_project/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render_to_response
2 | from humandt.fields import HumanDateTimeField, HumanTimeField, HumanDateField
3 | from django.forms import Form
4 | from django.template import RequestContext
5 |
6 | class ExampleForm(Form):
7 | datetime = HumanDateTimeField(required=False)
8 | time = HumanTimeField(required=False)
9 | date = HumanDateField(required=False)
10 |
11 | def example(request):
12 | dates = None
13 | if request.method == 'POST':
14 | form = ExampleForm(request.POST)
15 | if form.is_valid():
16 | dates = form.cleaned_data
17 | else:
18 | form = ExampleForm()
19 | return render_to_response('example.html', {
20 | 'form': form,
21 | 'dates': dates,
22 | 'input': request.POST.copy(),
23 | }, context_instance=RequestContext(request))
24 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from distutils.core import setup
2 | from humandt import __version__
3 |
4 | setup(name='django-human-datetime',
5 | version=__version__,
6 | description='Uses the parsedatetime package to parse human readable date/time expressions into Django fields',
7 | long_description=open('README.rst').read(),
8 | author='Justin Quick',
9 | author_email='justquick@gmail.com',
10 | url='http://github.com/justquick/django-human-datetime',
11 | packages=['humandt'],
12 | install_requires=['django', 'parsedatetime','pytz',],
13 | classifiers=['Development Status :: 4 - Beta',
14 | 'Environment :: Web Environment',
15 | 'Intended Audience :: Developers',
16 | 'License :: OSI Approved :: Apache Software License',
17 | 'Operating System :: OS Independent',
18 | 'Programming Language :: Python',
19 | 'Programming Language :: Python :: 3',
20 | 'Topic :: Utilities'],
21 | )
22 |
--------------------------------------------------------------------------------
/humandt/fields.py:
--------------------------------------------------------------------------------
1 | from django.core import validators
2 | from django.core.exceptions import ValidationError
3 | from django.forms.fields import DateField, TimeField, DateTimeField
4 | from .parser import parse
5 |
6 | class HumanDateTimeField(DateTimeField):
7 | def to_python(self, value):
8 | if value in validators.EMPTY_VALUES:
9 | return None
10 | try:
11 | return parse(value)
12 | except Exception as e:
13 | raise ValidationError(self.error_messages['invalid'])
14 |
15 | class HumanTimeField(TimeField):
16 | def to_python(self, value):
17 | if value in validators.EMPTY_VALUES:
18 | return None
19 | try:
20 | return parse(value).time()
21 | except Exception as e:
22 | raise ValidationError(self.error_messages['invalid'])
23 |
24 | class HumanDateField(DateField):
25 | def to_python(self, value):
26 | if value in validators.EMPTY_VALUES:
27 | return None
28 | try:
29 | return parse(value).date()
30 | except Exception as e:
31 | raise ValidationError(self.error_messages['invalid'])
32 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | Django Human DateTime Parsing
2 | ==============================
3 |
4 | :Authors:
5 | Justin Quick
6 | :Version: 0.1
7 |
8 | This tool uses the `parsedatetime package `_ to turn human readable form input (like 'tomorrow 7PM') into ``datetime`` objects (like datetime.datetime(2010, 4, 9, 19, ...)).
9 | This app requires ``parsedatetime`` and ``pytz``.
10 | The app comes with a set of fields to replace Django's own DateTimeField, DateField, and TimeField. Get them by using::
11 |
12 | from humandt.fields import HumanDateTimeField, HumanTimeField, HumanDateField
13 |
14 | Then use them however you like as form fields in your own Django Forms::
15 |
16 | from django.forms import Form
17 |
18 | class ExampleForm(Form):
19 | datetime = HumanDateTimeField(required=False)
20 | time = HumanTimeField(required=False)
21 | date = HumanDateField(required=False)
22 |
23 | Example Project
24 | ================
25 |
26 | Download the most recent sourcecode and start up the development server. Make sure you have the most recent version of django::
27 |
28 | git clone git://github.com/justquick/django-human-datetime.git
29 | cd django-human-datetime
30 | pip install parsedatetime pytz django
31 | python setup.py install
32 | cd example_project
33 | python manage.py runserver
34 |
35 | If all goes well it will be available at http://127.0.0.1:8000/. There is an example form up there that just spits out the parsed date/time input. Look at the example_project.views for useage example.
36 | To test the humandt app, stop the server and run this::
37 |
38 | python manage.py test humandt
39 |
40 |
41 | Tested working with Django 1.5.
42 |
--------------------------------------------------------------------------------
/example_project/settings.py:
--------------------------------------------------------------------------------
1 | # Django settings for example_project project.
2 |
3 | DEBUG = True
4 | TEMPLATE_DEBUG = DEBUG
5 |
6 | import os, sys
7 |
8 | ROOT = os.path.dirname(__file__)
9 | sys.path.insert(0, os.path.abspath(os.path.join(ROOT, '..')))
10 |
11 | ADMINS = (
12 | # ('Your Name', 'your_email@domain.com'),
13 | )
14 |
15 | MANAGERS = ADMINS
16 |
17 | DATABASES = {
18 | 'default': {
19 | 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
20 | 'NAME': 'dev.db', # Or path to database file if using sqlite3.
21 | }
22 | }
23 |
24 | # Local time zone for this installation. Choices can be found here:
25 | # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
26 | # although not all choices may be available on all operating systems.
27 | # On Unix systems, a value of None will cause Django to use the same
28 | # timezone as the operating system.
29 | # If running in a Windows environment this must be set to the same as your
30 | # system time zone.
31 | TIME_ZONE = 'US/Eastern'
32 |
33 | # Language code for this installation. All choices can be found here:
34 | # http://www.i18nguy.com/unicode/language-identifiers.html
35 | LANGUAGE_CODE = 'en-us'
36 |
37 | SITE_ID = 1
38 |
39 | # If you set this to False, Django will make some optimizations so as not
40 | # to load the internationalization machinery.
41 | USE_I18N = False
42 |
43 | # If you set this to False, Django will not format dates, numbers and
44 | # calendars according to the current locale
45 | USE_L10N = True
46 |
47 | # Absolute path to the directory that holds media.
48 | # Example: "/home/media/media.lawrence.com/"
49 | MEDIA_ROOT = os.path.join(ROOT, 'media')
50 |
51 | # URL that handles the media served from MEDIA_ROOT. Make sure to use a
52 | # trailing slash if there is a path component (optional in other cases).
53 | # Examples: "http://media.lawrence.com", "http://example.com/media/"
54 | MEDIA_URL = '/media/'
55 |
56 | # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
57 | # trailing slash.
58 | # Examples: "http://foo.com/media/", "/media/".
59 | ADMIN_MEDIA_PREFIX = '/media/admin/'
60 |
61 | # Make this unique, and don't share it with anybody.
62 | SECRET_KEY = 'v6c(-rjc%((mu)xw1m!#^uhhwjmldihpyaud6i&*hd(i1k_^8m'
63 |
64 | # List of callables that know how to import templates from various sources.
65 | TEMPLATE_LOADERS = (
66 | 'django.template.loaders.filesystem.Loader',
67 | 'django.template.loaders.app_directories.Loader',
68 | # 'django.template.loaders.eggs.Loader',
69 | )
70 |
71 | MIDDLEWARE_CLASSES = (
72 | 'django.middleware.common.CommonMiddleware',
73 | 'django.contrib.sessions.middleware.SessionMiddleware',
74 | 'django.middleware.csrf.CsrfViewMiddleware',
75 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
76 | 'django.contrib.messages.middleware.MessageMiddleware',
77 | )
78 |
79 | ROOT_URLCONF = 'example_project.urls'
80 |
81 | TEMPLATE_DIRS = (
82 | os.path.join(ROOT, 'templates'),
83 | )
84 |
85 | INSTALLED_APPS = (
86 | 'django.contrib.auth',
87 | 'django.contrib.contenttypes',
88 | 'django.contrib.sessions',
89 | 'django.contrib.sites',
90 | 'django.contrib.messages',
91 | 'django.contrib.admin',
92 | 'humandt',
93 | )
94 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | Copyright 2010 Justin Quick
179 |
180 | Licensed under the Apache License, Version 2.0 (the "License");
181 | you may not use this file except in compliance with the License.
182 | You may obtain a copy of the License at
183 |
184 | http://www.apache.org/licenses/LICENSE-2.0
185 |
186 | Unless required by applicable law or agreed to in writing, software
187 | distributed under the License is distributed on an "AS IS" BASIS,
188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189 | See the License for the specific language governing permissions and
190 | limitations under the License.
191 |
192 |
--------------------------------------------------------------------------------