【问题标题】:Custom date widget in django?Django中的自定义日期小部件?
【发布时间】:2014-06-19 05:18:48
【问题描述】:

在我当前基于 python 和 django 的应用程序中,我为日期创建了一个自定义小部件。

from datetime import date
from django.forms import widgets

class DateSelectorWidget(widgets.MultiWidget):
    def __init__(self, attrs=None):
        # create choices for months, years
        # example below, the rest snipped for brevity.
        years = [(year, year) for year in range(1945, 2016)]        
        months = [(1,'Jan'),(2,'Feb')]
        _widgets = (        
            widgets.Select(attrs=attrs, choices=months),
            widgets.Select(attrs=attrs, choices=years),
        )
        super(DateSelectorWidget, self).__init__(_widgets, attrs)

    def decompress(self, value):
        if value:
            return [value.month, value.year]
        return [None, None]

    def format_output(self, rendered_widgets):
        return u''.join(rendered_widgets)

    def value_from_datadict(self, data, files, name):
        datelist = [
            widget.value_from_datadict(data, files, name + '_%s' % i)
            for i, widget in enumerate(self.widgets)]
        try:
            D = date(day=1, month=int(datelist[0]),
                    year=int(datelist[1]))
        except ValueError:
            return ''
        else:
            return str(D) 

在加载表单时它工作正常(返回日期对象),但是当我提交表单并将表单中的某些字段留为空时,我收到以下错误。

Caught AttributeError while rendering: 'str' object has no attribute 'month'

Request Method:     POST
Request URL:    
Django Version:     1.3.1
Exception Type:     TemplateSyntaxError
Exception Value:    

Caught AttributeError while rendering: 'str' object has no attribute 'month'

Exception Location:     /var/www/stacks/django-apps/kkk/apps/oooomonth_year.py in decompress, line 21

【问题讨论】:

    标签: python django


    【解决方案1】:

    你在这里得到了错误,

    def decompress(self, value):
            if value:
                return [value.month, value.year]
            return [None, None]
    

    value 对象没有月份属性。如果你想知道值属性print dir(value)。在这个值中是一个字符串。

    更新:

    检查属性hasattr(value, 'month')。希望对您有所帮助。

    【讨论】:

    • 在加载表单时工作正常(返回日期对象),但是当我提交表单并将表单中的某些字段留空时,我收到以下错误。
    • 嘿,然后使用 dir 检查该对象的属性(即值)。
    【解决方案2】:

    它是在 post 数据绑定到表单时产生的。 (由于验证消息或任何其他问题未存储到数据库中)。因为

    def decompress(self, value):
            if value:
                return [value.month, value.year]
            return [None, None]
    

    上述方法仅在日期存储到数据库时处理日期。但是当表单没有成功提交时,它的行为就像“Str object”。所以你需要通过下面定义的方法来更新上面的方法:

    def decompress(self, value):
            if value:
                import types
                try:
                    if type(value) == types.StringType:
                        from datetime import datetime as dt
                        tmp_date = dt.strptime(value, '%Y-%m-%d')
                        return [tmp_date.month, tmp_date.year]
                    else:
                        return [value.month, value.year]
                except:
                    raise
            else:
                return [None, None]
    

    现在这个方法将处理表单提交或不提交的两种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-23
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 2012-03-28
      • 2013-04-03
      相关资源
      最近更新 更多