Django 子类化 multiwidget - 使用自定义 multiwidget 重建帖子上的日期

发布于 2024-10-11 20:05:07 字数 1694 浏览 1 评论 0原文

我的 django 书又回到了大学,我正在努力解决这本书。

我像这样对 django.forms.widgets.MultiWidget 进行了子类化:

class DateSelectorWidget(widgets.MultiWidget):
    def __init__(self, attrs=None, dt=None, mode=0):  
        if dt is not None:
            self.datepos = dt
        else:
            self.datepos = date.today()    

        # bits of python to create days, months, years
        # example below, the rest snipped for neatness.

        years = [(year, year) for year in year_digits]

        _widgets = (
            widgets.Select(attrs=attrs, choices=days), 
            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.day, value.month, value.year]
        return [None, None, None]

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

这给了我一个漂亮的日期选择字段,如下所示: 漂亮的日期选择

我的问题真的很简单。当我将所述表单提交到其处理方法时(使用如下过程:

forminstance = ModelNameForm(request.POST, instance=modelinstance)
    if forminstance.is_valid():
        forminstance.save()

这会失败,因为 Django 不知道如何获取我的多小部件并将其转换回基础字段类型,该类型在 中设置)显然

,django 源代码中有关 MultiWidget 的注释给了我这个有用的提示:

<块引用>

您可能希望将此类与 MultiValueField 一起使用。

但问题是——我可能不这么认为。我想保留我的 DateField() 因为它非常有用并且没有必要重复它。然后我需要做的是以某种方式将这些多个字段转换回单个有效的日期字符串(yyyy-mm-dd)以插入数据库。

那么我的问题是:

如何?实现这一目标的最佳方法是什么?

So my django book is back at university and I'm struggling to work this one out.

I've subclassed django.forms.widgets.MultiWidget like so:

class DateSelectorWidget(widgets.MultiWidget):
    def __init__(self, attrs=None, dt=None, mode=0):  
        if dt is not None:
            self.datepos = dt
        else:
            self.datepos = date.today()    

        # bits of python to create days, months, years
        # example below, the rest snipped for neatness.

        years = [(year, year) for year in year_digits]

        _widgets = (
            widgets.Select(attrs=attrs, choices=days), 
            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.day, value.month, value.year]
        return [None, None, None]

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

Which gives me a nifty looking date selection field like so:
Nifty looking date selection thing

My queston is very simple really. When I submit said form to its handling method (which uses a process like this:

forminstance = ModelNameForm(request.POST, instance=modelinstance)
    if forminstance.is_valid():
        forminstance.save()

This fails, because Django doesn't know how to take my multi-widget and convert it back to the underlying field type, which is set in models.py to DateField(), clearly.

Now, the comments around the MultiWidget in the django source give me this useful hint:

You'll probably want to use this class with MultiValueField.

But the thing is - I probably don't. I want to keep my DateField() because it is very useful and there is no point duplicating it. What I need to do then is somehow convert these multiple fields back into a single valid datestring (yyyy-mm-dd) for insertion into the database.

My question is then:

How? What is the best way to achieve this?

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

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

发布评论

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

评论(1

小ぇ时光︴ 2024-10-18 20:05:07

回答了我自己的问题!

我实现了这个方法:

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=int(datelist[0]), month=int(datelist[1]), \
             year=int(datelist[2]))
        return str(D)
    except ValueError:
        return ""

value_from_datadict从整个帖子数据字典中提取所有子小部件的数据。我所做的是提取各种日期对应项,并使用日期构造函数来验证日期。如果有效,我们以正确的格式打印字符串,否则,我们返回一个空字符串,该空字符串

forminstance.is_valid()

将被捕获。

当我这样做时我喜欢它!

Answered my own question!

I implemented this method:

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=int(datelist[0]), month=int(datelist[1]), \
             year=int(datelist[2]))
        return str(D)
    except ValueError:
        return ""

value_from_datadict pulls the data of all the sub-widgets from the entire post datadict. What I've done is to extract out the various date counterparts, and use the date constructor to validate the date. If it is valid, we print the string out in the correct format, otherwise, we return an empty string which

forminstance.is_valid()

will catch.

I love it when I do this!

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