Публикации с меткой «newforms»

Еще один блог о Django

Ну это просто праздник какой-то!

Django's newforms-admin branch merged into trunk

Лирическое отступление: Знаете, меня сейчас переполняют настолько положительные эмоции, что их просто невозможно как-то точно сформулировать и/или описать.

Но если по сути, то бранч newforms-admin уже давно заслужил быть слитым в транк. Почему?

  1. Потому что, кастомизация административной панели Django переходит на совершенно новый уровень.
  2. Потому что, один сайт != одна административная панель Джанго.
  3. Потому что, class Media для форм! И теперь для добавления кастомного CSS или JavaScript не надо реализовывать свой велосипед.
  4. Потому что, формсеты.
  5. Да и просто потому что, oldforms – это уже история.

И что самое главное, каких-то экстра трудностей по переходу на newforms-admin наблюдаться не должно. А если еще не использовал в проектах встроенную админку – то их вообще не будет ;)

upd. Не так много времени прошло после мерджинга newforms-admin в trunk, как была выпущена первая альфа 1.0 релиза Django, и вместе с тем библиотека django.newforms тоже стала историей ;) Отныне есть только The forms library.

Еще один блог о Django

Расширение виджета для выбора даты в Django

В предыдущем посте я упомянул о виджете для выбора даты в Django. И все вроде бы хорошо, но этот виджет становится совершенно бесполезным, когда надо:

  • выбрать месяц день и год в другом порядке (например, в привычном день-месяц-год);
  • использовать трехбуквенные сокращения месяца, а не полное название
  • не выбирать день (например, май 2008)
  • не выбирать ни день, ни месяц (например, 2008 год)
  • добавить первым пустой <option>

И потому для этих случаев я смастерил очередной велосипед свой виджет, который устраняет все эти недостатки. Посмотреть как он работает можно здесь (поля Дата рождения, Год поступления, Год окончания, Период работы с, по).

Уже интересно?

Тогда получайте сам виджет:

import datetime, re
from time import strptime

from django.newforms.widgets import Widget, Select
from django.utils.dates import MONTHS, MONTHS_3
from django.utils.safestring import mark_safe

PATTERNS = (
    ('%b', 'month'),
    ('%B', 'month'),
    ('%d', 'day'),
    ('%m', 'month'),
    ('%y', 'year'),
    ('%Y', 'year'),
)

class SelectDateWidget(Widget):
    """
    Extended version of django.newforms.extras.SelectDateWidget

    The main advantages are:
    - Widget can splits date input into custom select boxes.
    - Custom select boxes can have first empty option.
    """
    day_field = '%s_day'
    month_field = '%s_month'
    year_field = '%s_year'

    def __init__(self, *args, **kwargs):
        """
        Optional arguments:

        format_separator - separator in input_format. By default: -
        input_format     - valid date input format. By default: %B-%d-%Y
        null             - adds first empty option to all selects. By
                           default: False
        years            - list/tuple of years to use in the "year" select
                           box. By default: this year and next 9 printed.
        """
        self.attrs = kwargs.get('attrs', {})
        self.format_separator = kwargs.get('format_separator', '-')
        self.input_format = kwargs.get('input_format', '%B-%d-%Y')
        self.null = kwargs.get('null', False)

        if 'years' in kwargs:
            self.years = kwargs['years']
        else:
            year = datetime.date.today().year
            self.years = range(year, year+10)

        fields = []
        parts = self.input_format.split(self.format_separator)

        for part in parts:
            for k, v in PATTERNS:
                if part == k:
                    fields.append((k, v))

        if not fields:
            raise TypeError('Date input format "%s" is broken.' % self.input_format)

        self.fields = fields
        self.input_format = self.input_format.replace('%b', '%m').replace('%B', '%m')

    def id_for_label(self, id_):
        return id_
    id_for_label = classmethod(id_for_label)

    def render(self, name, value, attrs=None):
        try:
            year, month, day = value.year, value.month, value.day
        except AttributeError:
            year = month = day = None

            if isinstance(value, basestring):
                try:
                    t = strptime(value, self.input_format)
                    year, month, day = t[0], t[1], t[2]
                except:
                    pass

        def _choices(pattern):
            if pattern == '%b':
                choices = MONTHS_3.items()
                choices.sort()
            elif pattern == '%B':
                choices = MONTHS.items()
                choices.sort()
            elif pattern == '%d':
                choices = [(i, i) for i in range(1, 32)]
            elif pattern == '%m':
                choices = [(i, i) for i in range(1, 13)]
            elif pattern == '%y':
                choices = [(i, str(i)[-2:]) for i in self.years]
            elif pattern == '%Y':
                choices = [(i, i) for i in self.years]

            if self.null:
                choices.insert(0, (None, mark_safe('&mdash;')))

            return tuple(choices)

        id_ = self.attrs.get('id', 'id_%s' % name)
        output = []

        for i, field in enumerate(self.fields):
            pattern, field_name = field
            field = getattr(self, '%s_field' % field_name)

            sel_name = field % name
            sel_value = locals().get(field_name, None)

            if i == 0:
                local_attrs = self.build_attrs(id=id_)
            else:
                local_attrs['id'] = field % id_

            sel = Select(choices=_choices(pattern)).render(sel_name, sel_value, local_attrs)
            output.append(sel)

        return mark_safe('\n'.join(output))

    def value_from_datadict(self, data, files, name):
        value = []

        for pattern, field_name in self.fields:
            field = getattr(self, '%s_field' % field_name)
            field_value = data.get(field % name, None)
            if field_value and field_value != 'None':
                value.append(str(field_value))

        if value:
            return '-'.join(value)

        return data.get(name, None)

p.s. Примеры использования виджета в упомянутой форме:

class CvForm(forms.Form):
    """ Some fields missed """
    g_birth_date = forms.DateField(label=_('Birth date'), initial=datetime.date.today,
        input_formats=('%d-%m-%Y',),
        widget=SelectDateWidget(input_format='%d-%B-%Y', years=range(year, year-101, -1)))
    e_from = forms.DateField(label=_('Entry year'), required=False, input_formats=('%Y',),
        widget=SelectDateWidget(input_format='%Y', years=range(year, year-51, -1), null=True))
    e_to = forms.DateField(label=_('Graduate year'), required=False, input_formats=('%Y'),
        widget=SelectDateWidget(input_format='%Y', years=range(year, year-51, -1), null=True))
    w_from = forms.DateField(label=_('Work from'), required=False, input_formats=('%m-%Y',),
        widget=SelectDateWidget(input_format='%B-%Y', years=range(year, year-51, -1), null=True))
    w_to = forms.DateField(label=_('Work to'), required=False, input_formats=('%m-%Y',),
        widget=SelectDateWidget(input_format='%B-%Y', years=range(year, year-51, -1), null=True))

Еще один блог о Django

Виджет для выбора даты в Django

Лежит в django.newforms.extras.widgets.SelectDateWidget

Пример использования:

import datetime

from django import newforms as forms
from django.newforms.extras.widgets import SelectDateWidget
from django.utils.translation import ugettext as _

year = datetime.date.today().year

class SampleForm(forms.Form):
    default_date = forms.DateField(label=_('Default date'), initial=datetime.date.today,
        help_text=_('Today date in text input.'))
    birth_date = forms.DateField(label=_('Birth date'), initial=datetime.date.today,
        help_text=_('Today date in 3 selects (each for day, month and year) with 100 latest years'),
        widget=SelectDateWidget(years=range(year, year-100, -1)))
    future_date = forms.DateField(label=_('Future date'), initial=datetime.date.today,
        help_text=_('Today date in 3 selects (each for day, month and year).'))

без применения всяких стилей эта форма будет выглядеть следующим образом:

Метки

.net .NET C# .sort 1.2 2009 2010 404 error admin ajax amazon analytics and apache api archlinux asp.net async asynchronous autocomplete bash blender blog blogengine blogs book bootstrap bot bpython buildout byteflow bzr C c plus plus C++ cache cbv Chaco checkio chrome ci ckeditor class based views clojure closure cms cms с удобной админкой code coding style collectd COM comet competition conference ConfigParser contest Context continuous integration CouchDB coverage CppCMS cpyext cpython crud csrf CSS ctypes curl custom model fields cx_freeze cython database db dbm dbqueries debian debug debugging decorator decorators deploy deployment descriptor design dev devconf developers development diveintopython Django django 1.2 django 1.3 django advent django framework django template django trunk django weblog django-admin-tools django-cms django-compressor django-hosts django-piston django-registration django-sphinx django.admin djangoadvent djangocms djangodash doc documentation drupal e-legion eclipse EGit emacs encoding Enthought epoll erlang event exception ExtJS fabric facebook fastcgi finaloption fixtures fonts forms formset fp framework freebsd freeswitch fs2web ftp fun funcparserlib functional gae gamin gandi generic views gettext gevent gil git github gitosis Google Google App Engine google picasa Google Translate google wave Google Web Toolkit grab grablab greenlet gtd gui haskell hg hgshelve highlighter host hosting how-to howto html html5lib Hudson humor i18n icfpc ide idiomatic image-scripting improvements Internet interpreter ipython ironpython izmenimsya.ru jabber java javascript jenkins jetbrains JIT job jquery json jstree jython kde kiev kiyv kyivpy l10n ldap library libs Life Links linux Linux & Unix LLVM logging logs lxml Mac OS X magic mail markdown Matplotlib Mayavi maybe mediavirus meetup memcache Memcached memory messages metaclass middleware migration mikrotik mkd model models mod_python mod_wsgi mongodb monitoring mptt musicmans.ru musicx mvc my-projects mysql netCDF networkx newforms newforms-admin news nginx Nhibernate nix nose NoSQL numpy oop open source OpenID openoffice opster optimization oracle orm os pagination parsing path patterns pdf PDF-принтер PEP PEP8 performance performance optimization perl personality photo php picture-driven computing PIL pinax pingback pip plasma plone plugin plugins postgresql programming progress bar psycopg2 py2exe pybb pybbm pycamp pycharm pycon pycow pycurl pydev pygtk pylons PyNGL pypy pyqt PyQt4 pyrad pyramid PySide Python Python 2.5 python 2.7 python 3 python c api python speed python-mssql python3 pywinauto Qt Qt4 queue rabbitmq radius raw sql re redis redsolution redsolution cms regexp regular expressions release repoze.bfg RequestContext reusable apps robokassa rss ru ruby ruby-on-rails sample satchmo scalability SciPy scraping screencast search selenium self.error seo server setattr settings setuptools shell sikuli sms snippet socket.io software sorting south sphinx spider sql sqlalchemy sqlite ssh startup step-by-step subdomain subversion svn SyntaxHighlighter system tags tdd tddspry teh drama template templates templatetags test testing thinkpad threading threads tips tips and tricks tools tornadio tornado tornado server tricks tutorial tweepy twisted twitter typography uapycon Ubuntu ucsvlog uml Uncategorized unicode unit test unit testing UnitTest Unladen Swallow upload urllib urls utf-8 uwsgi validation vcs versioning video vim virtualenv Visual Studio vkontakte voip wave web web-devel web-services web-разработка webdev webfaction webkit webpy websockets webtest widget widgets Win API windows Wirbel work wrapper wsgi wxPython wxWidgets wysiwyg xapian xml xmonad xmpp xpath yandex youtube zip zomg zope [cdata[cbv]] [cdata[ci]] [cdata[class based views]] [cdata[continuous integration]] [cdata[django framework]] [cdata[django-sphinx]] [cdata[django]] [cdata[nginx]] [cdata[python]] [cdata[virtualenv]] [cdata[программирование]] автоматизация администрирование администрирование django админка алгоритмы архитектура атрибуты базы данных Без рубрики безопасность библиотеки блоге бот веб-разработка видео Визуализация данных вконтакте Все записи гвидо ван россум граббер графика графы декоратор декораторы дескриптор дескрипторы документация заметки игра жизнь идея интересное киев Клиентам книги конференция личное математика метаклассы модели модули монады морфология мысли невозможное новости о облачные вычисления обо мне Обработка данных оптимизация оптимизация кода Основная лента основы парсинг парсинг сайтов перевод песочница Питон поебень поиск правила кодирования программирование Проектирование производительность работа рабочее размышлизмы Разное разработка разработка приложений разработки регулярные выражения сайт событие события ссылки статьи тестирование тесты Тюмень убунтариум фигня философия формы форум Хабрахабр хакинг хостинг шаблоны шаблоны проектирования эксперимент Эксперименты юмор я пиарюсь Яндекс