Django SelectDateWidget 仅显示月份和年份

发布于 2024-10-12 10:33:21 字数 80 浏览 2 评论 0原文

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

目前使用 SelectDateWidget。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

秋凉 2024-10-19 10:33:21

此处有一个片段,它将日期设置为 1 (假设您我有一个 DateField这个值最终会达到,你需要得到某种一天)。

代码是这样的(以防 Django 片段消失):

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)

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)
方圜几里 2024-10-19 10:33:21

这里有一个 Python 3 小部件示例 https://djangosnippets.org/snippets/10522/

用法示例:

class myForm(forms.Form):
    # ...
    date = forms.DateField(
        required=False,
        widget=MonthYearWidget(years=xrange(2004,2010))
    )

A Python 3 widget sample here https://djangosnippets.org/snippets/10522/.

Example usage :

class myForm(forms.Form):
    # ...
    date = forms.DateField(
        required=False,
        widget=MonthYearWidget(years=xrange(2004,2010))
    )
笛声青案梦长安 2024-10-19 10:33:21

我今天遇到了同样的问题,并通过通过 css 属性删除日期字段并将 1 设置为清理时的日期值来解决它。

#id_my_date_field_day-button {
    display: none;
}

我使用带有 UpdateView 的 ModelForm,因此在我的字段中有初始数据,这使生活变得更简单,因为我总是有 my_date_field 当天的有效值。

I came across the same problem today and solved it by removing the day field via a css property and setting 1 as value for the day on clean up.

#id_my_date_field_day-button {
    display: none;
}

I used a ModelForm with an UpdateView and therefore had initial data in my fields which made life a bit simpler because I always had a valid value for the day of my_date_field.

梦初启 2024-10-19 10:33:21

我编写了一个更简单的版本(https://djangosnippets.org/snippets/10943/)继承自 django 内置 SelectDateWidget

在 widgets.py 中:

import calendar
import datetime

from django.forms.widgets import HiddenInput, SelectDateWidget
from django.utils import datetime_safe
from django.utils.formats import get_format


class MonthYearWidget(SelectDateWidget):
    def __init__(self, last_day=False, *args, **kwargs):
        self.last_day = last_day
        return super().__init__(*args, **kwargs)

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        day_name = self.day_field % name
        day_subwidget = HiddenInput().get_context(
            name=day_name,
            value=1,
            attrs={**context["widget"]["attrs"], "id": "id_%s" % day_name},
        )
        context["widget"]["subwidgets"][0] = day_subwidget["widget"]

        return context

    def value_from_datadict(self, data, files, name):
        value = super().value_from_datadict(data, files, name)
        if self.last_day is True:
            y = data.get(self.year_field % name)
            m = data.get(self.month_field % name)
            if y is not None and m is not None:
                input_format = get_format("DATE_INPUT_FORMATS")[0]
                monthrange = calendar.monthrange(int(y), int(m))
                date_value = datetime.date(int(y), int(m), monthrange[1])
                date_value = datetime_safe.new_date(date_value)
                return date_value.strftime(input_format)
        return value

kwargs:

  • last_day :如果设置为 True,则返回该月的最后一天生成的日期,否则返回从该月第一天开始的日期

使用示例:

# models.py
from django.db import models
from django.utils.translation import gettext_lazy as _

class MyModel(models.Model):
    start = models.DateField(
        _("Start date"),
    )

    end = models.DateField(
        _("End date"),
    )

    class Meta:
        verbose_name = _("My model")

# forms.py
from django import forms
from .models import MyModel
from .widgets import MonthYearWidget


class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        exclude = []

        widgets = {
            "start": MonthYearWidget(),
            "end": MonthYearWidget(last_day=True),
        }

I've written a simpler version (https://djangosnippets.org/snippets/10943/) inheriting from django built-in SelectDateWidget.

In widgets.py:

import calendar
import datetime

from django.forms.widgets import HiddenInput, SelectDateWidget
from django.utils import datetime_safe
from django.utils.formats import get_format


class MonthYearWidget(SelectDateWidget):
    def __init__(self, last_day=False, *args, **kwargs):
        self.last_day = last_day
        return super().__init__(*args, **kwargs)

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        day_name = self.day_field % name
        day_subwidget = HiddenInput().get_context(
            name=day_name,
            value=1,
            attrs={**context["widget"]["attrs"], "id": "id_%s" % day_name},
        )
        context["widget"]["subwidgets"][0] = day_subwidget["widget"]

        return context

    def value_from_datadict(self, data, files, name):
        value = super().value_from_datadict(data, files, name)
        if self.last_day is True:
            y = data.get(self.year_field % name)
            m = data.get(self.month_field % name)
            if y is not None and m is not None:
                input_format = get_format("DATE_INPUT_FORMATS")[0]
                monthrange = calendar.monthrange(int(y), int(m))
                date_value = datetime.date(int(y), int(m), monthrange[1])
                date_value = datetime_safe.new_date(date_value)
                return date_value.strftime(input_format)
        return value

kwargs:

  • last_day : if set to True, returns the last day of the month in the generated date, otherwise returns a date starting from the 1st day of the month

Usage example:

# models.py
from django.db import models
from django.utils.translation import gettext_lazy as _

class MyModel(models.Model):
    start = models.DateField(
        _("Start date"),
    )

    end = models.DateField(
        _("End date"),
    )

    class Meta:
        verbose_name = _("My model")

# forms.py
from django import forms
from .models import MyModel
from .widgets import MonthYearWidget


class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        exclude = []

        widgets = {
            "start": MonthYearWidget(),
            "end": MonthYearWidget(last_day=True),
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文