Django自定义字段用于仅使用月份和年份来处理日期字段 [英] Django custom field to handle datefield with only month and year

查看:346
本文介绍了Django自定义字段用于仅使用月份和年份来处理日期字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

----------------编辑--------------------

我无法使用自定义模型字段来完成此操作,因此我不得不继续前进,所以实际上,我以本文结尾处指定的另一种方式进行了此操作。

I could not succed doing it with Custom Model Field and I had to move on, so actually, I did it the alternative way specified at the end of this post.

此处是新链接

----------------结束编辑----- ---------------

我的应用程序显示表单集,用户可以在其中创建对象。验证后,将再次显示该表单集,用户可以添加新对象。

My app displays formsets where users can create objects. Once validated, the formset is displayed again and user can add new objects.

日期只能是月份和年份(%m /%Y)。

Dates should only be month and year ("%m/%Y").

我可以在输入字段(尽管使用jquery)上在输入的日期前添加 01 /。但是提交后,该字段现在显示为%d /%m /%Y(正常)。

I could work on the input field (though jquery) to add '01/' in front of the date entered. But after submitting, the field now displays "%d/%m/%Y" (normal).

因此,我正在寻找一种翻译输入字符串的方法(例如:09/2018)到dateField以存储在数据库中,然后在从数据库中检索数据时将此dateField转换为字符串。

So, I'm looking for a way to translate input string (ex : 09/2018) to dateField to store in the database, and then a translate this dateField to string when datas are retrieved from database.

我知道,我可以只需使用一个表单charfield几个月,再使用一个表单charfield多年。

I know, I could simply use a form charfield for months and another one for years.

但是我想将其保留为日期对象,因此,在模板中,我可以执行日期格式化({{edu.start_date | date: D,d M,Y}})

But I would like to keep it as a date object, so, in templates, I could perform date formatting ({{ edu.start_date |date:"D, d M, Y" }})

Django定制模型字段为此发出的声音: Django自定义模型字段

我可以在自定义字段:

def string_to_date(value):
    value = '01/' + value
    la_date = datetime.strptime(value, "%d/%m/%Y").date()
    return la_date

def date_to_string(la_date_date):
    la_date_str = la_date_date.strftime('%m/%Y')
    return la_date_str

class DateYearMonth(models.DateField):
    def get_prep_value(self, value):
        if value is None:
            return value
        return string_to_date(value)

    def to_python(self, value):
        if value is None:
            return value
        return date_to_string(value)

关联的表单(我评论过的小部件):

The form associated (i commented widgets):

class EducationForm(forms.ModelForm):
    start_date =  forms.CharField()
    end_date = forms.CharField()

    class Meta:
        model = Education
        exclude = ("curriculum",)

        #     # les widgets :
       #       widgets = {
        #          'start_date': forms.TextInput(),
        #          'end_date': forms.TextInput(),
#     }

嗯,到目前为止这还行不通。但是我什至不知道我是否朝着正确的方向前进...

Well, this does not work so far. But I don't even know if I'm heading to the right direction...

EDIT

实际上,也许我可以使用简单的charfield来表示月份和年份,并添加一个可以从中创建日期的模型方法(也许是@property)...这样,我可以使它保持简单表单并可以在模板上设置格式。

Actually, maybe I could use simple charfield for month and year and add a model method that would create a date out of it (maybe a @property)... This way, I would keep it simple on the form and be able to format on the templates...

推荐答案

您可以将Year设置为IntegerField和Month(CharField或整数)并分别存储Year(月份)可能是最好的解决方案。
下面仅是一个示例(年份为DatetimeField到YearField)

You can make the Year an IntegerField and Month (CharField or Integer) and store Year in Months individually is probably the best solution. Below is an example fore Year only(kind of DatetimeField to YearField)

import datetime
    YEAR_CHOICES = []
    for r in range(1980, (datetime.datetime.now().year+1)):
        YEAR_CHOICES.append((r,r))

    year = models.IntegerField(_('year'), choices=YEAR_CHOICES, 
           default=datetime.datetime.now().year)

这篇关于Django自定义字段用于仅使用月份和年份来处理日期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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