Django SelectDateWidget仅显示月份和年份 [英] Django SelectDateWidget to show month and year only

查看:170
本文介绍了Django SelectDateWidget仅显示月份和年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



目前使用的是SelectDateWidget吗?

是否有不同的小部件或参数,将允许django仅显示/取代年,月输入而不是年,月和日?

解决方案

有一个片段这里,将日期设置为 1 (假设您有一个 DateField 这个值最终会出现,你需要



代码就是这样(只是为了防止Django代码段消失):

  import datetime 
import re

from django.forms.widgets import Widget,从django.utils.dates导入
导入MONTHS
from django.utils.safestring import mark_safe

__all__ =('MonthYearWidget',)

RE_DATE = re.compile(r'(\d {4}) - (\d\ d?) - (\d\d?)$')

class MonthYearWidget(Widget):

将日期输入分成两个的小部件;选择>月份和年份的框,
与当天默认为每月的第一个月。

基于SelectDateWidget,在

django / trunk / django / forms / extras / widgets.py



none_value =(0,'---')
month_field ='%s_month'
year_field ='%s_year'

def __init __(self,attrs = None ,年=无,必需=真):
#年是在年选择框中使用的年份的可选列表/元组
self.attrs = attrs或{}
self.required = required
如果年份:
self.years =年
其他:
this_year = datetime.date.today()。year
self.years =范围(this_year,this_year + 10)

def render(self,name,value,attrs = None):
try:
year_val,month_val = value.year,value。月
除了AttributeError:
year_val = month_val = None
如果isinstance(value,basestring):
match = RE_DATE.match(value)
如果匹配:
year_val,month_val,day_val = [int(v)for v in match.groups()]

output = []

if'id 'in self.attrs:
id_ = self.attrs ['id']
else:
id_ ='id_%s'%name

month_choices = MONTHS
如果没有(self.required和value):
month_choices.append(self.none_value)
month_choices.sort()
local_attrs = self.build_attrs(id = self.month_field%id_)
s =选择(choices = month_choices)
select_html = s.render(self.month_field%name,month_val,local_attrs)
output.append(select_html)

year_choices = [(i,i)for self in self.years]
if not(self.required and value):
year_choices.insert(0,self.none_value)
local_attrs ['id'] = self.year_field%id_
s =选择(choices = year_choices)
select_html = s.render(self.year_field%name,year_val,local_attrs)
output.append(select_html)

return mark_safe(u'\\\
'.join )

def id_for_label(self,id_):
return'%s_month'%id_
id_for_label = classmethod(id_for_label)

def value_from_datadict自我,数据,文件,名称)
y = data.get(self.year_field%name)
m = data.get(self.month_field%name)
如果y == m == 0:
return无
如果y和m:
返回'%s-%s-%s'%(y,m,1)
return data.get (名称,无)


Is there a different widget or argument that will allow django to only show/take the year and month input instead of year, month and day?

Currently using SelectDateWidget.

解决方案

There's a snippet here, which sets the day to 1 (presuming you've got a DateField that this value will end up in, you'll need to get some kind of day).

The code is like this (just in case Django snippets disappears):

import datetime
import re

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

__all__ = ('MonthYearWidget',)

RE_DATE = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$')

class MonthYearWidget(Widget):
    """
    A Widget that splits date input into two <select> boxes for month and year,
    with 'day' defaulting to the first of the month.

    Based on SelectDateWidget, in 

    django/trunk/django/forms/extras/widgets.py


    """
    none_value = (0, '---')
    month_field = '%s_month'
    year_field = '%s_year'

    def __init__(self, attrs=None, years=None, required=True):
        # years is an optional list/tuple of years to use in the "year" select box.
        self.attrs = attrs or {}
        self.required = required
        if years:
            self.years = years
        else:
            this_year = datetime.date.today().year
            self.years = range(this_year, this_year+10)

    def render(self, name, value, attrs=None):
        try:
            year_val, month_val = value.year, value.month
        except AttributeError:
            year_val = month_val = None
            if isinstance(value, basestring):
                match = RE_DATE.match(value)
                if match:
                    year_val, month_val, day_val = [int(v) for v in match.groups()]

        output = []

        if 'id' in self.attrs:
            id_ = self.attrs['id']
        else:
            id_ = 'id_%s' % name

        month_choices = MONTHS.items()
        if not (self.required and value):
            month_choices.append(self.none_value)
        month_choices.sort()
        local_attrs = self.build_attrs(id=self.month_field % id_)
        s = Select(choices=month_choices)
        select_html = s.render(self.month_field % name, month_val, local_attrs)
        output.append(select_html)

        year_choices = [(i, i) for i in self.years]
        if not (self.required and value):
            year_choices.insert(0, self.none_value)
        local_attrs['id'] = self.year_field % id_
        s = Select(choices=year_choices)
        select_html = s.render(self.year_field % name, year_val, local_attrs)
        output.append(select_html)

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

    def id_for_label(self, id_):
        return '%s_month' % id_
    id_for_label = classmethod(id_for_label)

    def value_from_datadict(self, data, files, name):
        y = data.get(self.year_field % name)
        m = data.get(self.month_field % name)
        if y == m == "0":
            return None
        if y and m:
            return '%s-%s-%s' % (y, m, 1)
        return data.get(name, None)

这篇关于Django SelectDateWidget仅显示月份和年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆