Django DateRangeField问题 [英] Django DateRangeField issue

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

问题描述

我有一个问题 DateRangeField 使用Forms插入数据库。

I have a problem with DateRangeField inserting to database using Forms.

model.py

from django.contrib.postgres.fields import DateRangeField
from django.db import models

class Event(models.Model):
    name = models.CharField(max_length=200)
    datefromto = DateRangeField() 

views.py

date_from = '2011-01-01'
date_to = '2011-01-31'
data = {
    "name" : "Test Name",
    "datefromto" : [date_from,date_to ]
}

form = Event_form(data)
if form.is_valid():
    form.save()
else:
    print(form.errors)

forms.py

class Event_form(forms.ModelForm):
    class Meta:
        model = Event
        fields = ('name','datefromto')

    def clean(self):
        print(self.cleaned_data)
        #{"name" : "Test Name"} there should be 'datefromto' key

当我打电话给form.is_valid()时,返回datefromto是必需的,它不应该是这样的,因为字典中有一个'datefromto'。当我尝试在表单清理功能中打印clean_data时,它只打印 {name:Test Name} 而不使用 datefromto 键。

When I call the form.is_valid() it returns "datefromto is required" it shouldn't be like this because there's a 'datefromto' inside the dictionary. When I try to print the cleaned_data in form clean function, it only prints {"name" : "Test Name"} without the datefromto key.

Django 1.9,Python 2.7和Postgre 9.3.14。

Django 1.9,Python 2.7 and Postgre 9.3.14.

推荐答案

在挖掘django源代码后,您应该为这样的范围字段追加数字后缀

After digging into the django source code, you should append number suffix for range field like that:

date_from = '2011-01-01'
date_to = '2011-01-31'
data = {
    "name" : "Test Name",
    "datefromto_0" : date_from,
    "datefromto_1" : date_to
}

form = Event_form(data)
if form.is_valid():
    form.save()
else:
    print(form.errors)

我已经使用 pdb 跟踪django内的代码,发现这个技巧...

I have used pdb to trace the code inside django, and found this trick...

当您下次在django中遇到其他问题时,可以使用 pdb 进行跟踪。它真的是一个伟大的工具,用于python调试...

And when you get stuck with other the issues in django next time, you can make use of pdb to trace. it is really a great tool for python debugging...

希望它会帮助... :)。

hope it would help... :).

这篇关于Django DateRangeField问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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