【问题标题】:Form with DateField: how to check for has_changed()带有 DateField 的表单:如何检查 has_changed()
【发布时间】:2016-09-26 11:19:04
【问题描述】:

Django 1.10.

尝试学习形式。

The problem is that I can't manage to make form.has_changed() become a False.

即 form.has_changed() 始终为 True。怀疑是原因在 DateField 中。因为 pub_date = forms.CharField() 给出了预期的 False 结果。

文档:https://docs.djangoproject.com/es/1.10/ref/forms/api/#django.forms.Form.has_changed

你能帮我踢一下吗:

1) 是因为 DateField 的原因吗?
2)如果是这样,为什么会这样?这 据我所知,实验中产生的形式是相同的。 3) 3)如何应对?

代码:

class PubDateForm(forms.Form):  
    pub_date = forms.DateField() 

pub_date_data = {'pub_date': '2015-01-01'}



form = PubDateForm(
                        pub_date_data, 
                        initial=pub_date_data
                       )
has_changed = form.has_changed()

实验:

pub_date_data = {'pub_date': '2015-01-01'}
form = PubDateForm(pub_date_data
#                , initial=pub_date_data
                       )
has_changed = form.has_changed()

PubDateForm: <tr><th><label for="id_pub_date">Pub date:</label></th><td><input id="id_pub_date" name="pub_date" type="text" value="2015-01-01" required /></td></tr>


pub_date_data = {'pub_date': '2015-01-01'}
form = PubDateForm(
# pub_date_data, 
                        initial=pub_date_data
                       )

PubDateForm: <tr><th><label for="id_pub_date">Pub date:</label></th><td><input id="id_pub_date" name="pub_date" type="text" value="2015-01-01" required /></td></tr>

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    在初始数据中使用date 对象而不是字符串

     pub_date_data = {'pub_date': date(2015, 1, 1)}
    

    请注意,重要的是initial 值是一个日期。如果您将表单数据作为字符串提供,如下例所示,则form.has_changed() 将返回False

    form = PubDateForm(data={'pub_date': '2015-01-01'},
                       initial={'pub_date': date(2015, 1, 1)}
                       )
    

    【讨论】:

      猜你喜欢
      • 2013-03-26
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      相关资源
      最近更新 更多