在我的Django应用程序中,程序从用户获取事件的时间,比如用户输入10:30事件的时间。该程序使用modelformset_factory来创建一大堆表单:
#forms.py
class EventForm(ModelForm):
class Meta:
model = Event
fields = ['entry', 'time', 'work']
localized_fields = ('time', )
widgets = {
'work': Textarea(attrs = {'cols': 40, 'rows': 8}),
}
#models.py
class Event(models.Model):
'''
Each day there are many events, e.g. at 10 am, the framer orders material, etc.
'''
entry = models.ForeignKey(Entry)
time = models.TimeField()
work = models.TextField()
#views.py:
EventFormSet = modelformset_factory( Event, form = EventForm, exclude = ('entry',),extra = 5)
eventset = self.EventFormSet(request.POST)
all_errors = eventset.errors # All errors returns [{}, {}, {}, {}, {}], so the data is free of error.
try:
eventset.is_valid()
except ValidationError:
return render(request, self.template_name, {'form': self.day_log(initial = self.initial_values), 'eventforms': self.event_formset})
events_instances = eventset.save(commit = False)
for instance in events_instances:
if instance.time:
event_date = datetime.date(the_year, the_month, the_day) # Naive date
event_time = instance.time # Naive time
naive_event_time = timezone.is_naive(event_time) # Checking naivaty
event_datetime = datetime.datetime.combine(event_date, event_time) # Naive datetime object
is_aware_event_datetime = timezone.is_aware(event_datetime) # Checking to see if the datetime object is aware or naive
event_aware_datetime = datetime.datetime(the_year, the_month, the_day, instance.time.hour, instance.time.minute, instance.time.second, tzinfo = pytz.utc) # Making an aware time
is_aware_event_aware_datetime = timezone.is_aware(event_aware_datetime) # Making sure the event_aware_datetime is indeed aware
instance.time = event_aware_datetime
awareness_test = timezone.is_aware(instance.time) # Making sure instance.time is aware
eventset.save() # Here is where the exception is thrown.
Django应用无法将时间数据保存到Postgres。异常类型是DataError,异常值为:
invalid input syntax for type timestamp with time zone:
LINE 1: ...y_event" ("entry_id", "time", "work") VALUES (14, '18:43:04....
,^指向'of '18:
编辑: 这是我的数据库:
CREATE TABLE site_activity_event
(
id serial NOT NULL,
entry_id integer NOT NULL,
"time" time without time zone NOT NULL,
work text NOT NULL,
CONSTRAINT site_activity_event_pkey PRIMARY KEY (id),
CONSTRAINT site_activity_event_entry_id_fkey FOREIGN KEY (entry_id)
REFERENCES site_activity_entry (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
我做了sqlall我的应用程序,以确保模型字段的数据类型对应于应用程序的数据类型,一切都很好。这似乎是一个postgres问题,但Django应该照顾Postgres(https://docs.djangoproject.com/en/1.8/topics/i18n/timezones/#migration-guide)所有那些讨厌的界面问题,所以这让我觉得我错过了一些东西。非常感谢任何帮助。
答案 0 :(得分:0)
那么,“18:43:04”是一个有时区的有效时间戳吗?你认为它指定了一个独特的时间点吗?如果你这样做,你就发现了PostgreSQL日期/时间处理中的一个主要错误。如果没有,那么您应该提供有效的时间戳或在数据库中使用正确的类型 - 如果不了解更多关于这些事件的话,我不能说出哪个。
答案 1 :(得分:0)
您的事件有一个TimeField,但看起来数据库是使用DateTimeField创建的。