使用:Python 3.10.4
Django 4.06
Django导入导出2.8.0
我正在尝试导入数据作为演示数据到我的django应用程序中。我一直得到一个错误localtime()不能应用于一个幼稚的日期时间(在解决了另一个我单独询问的错误之后)。我不担心这个特定的字段是幼稚的日期时间。它是一个需要在实际应用程序中手动设置的字段。
### models.py
class Reservation(models.Model):
reservation = models.OneToOneField(Vehicle, on_delete=models.CASCADE, primary_key=True,)
delivered = models.BooleanField('Delivered',default=False)
date_reserved = models.DateTimeField('date reserved', default=datetime.datetime.now)
...
### admin.py
class ReservationResource(resources.ModelResource):
class Meta:
model = Reservation
exclude = ('id',)
import_id_fields = ('reservation',)
fields = (
'reservation',
'delivered',
'date_reserved',
...
)
class ReservationImportExport(ImportExportModelAdmin):
resource_class: ReservationResource
@admin.register(Reservation)
class ReservationAdmin(SimpleHistoryAdmin, ReservationImportExport):
fields = ["delivered","date_reserved",...]
### demo-reservations.yaml (Note: Problem happens using different data file formats)
- reservation: 50001
delivered: False
date_reserved: 7/15/2022T00:00:00+00:00
...
以下是错误(稍微模糊)
Line number: 1 - localtime() cannot be applied to a naive datetime
50001, False, 7/15/2022T00:00:00+00:00, CHRIS EDWARDS, 16, ROSE TYLER
Traceback (most recent call last):
File "c:\Users\...\lib\site-packages\import_export\resources.py", line 670, in import_row
diff = self.get_diff_class()(self, original, new)
File "c:\Users\...\lib\site-packages\import_export\resources.py", line 221, in __init__
self.left = self._export_resource_fields(resource, instance)
File "c:\Users\...\lib\site-packages\import_export\resources.py", line 242, in _export_resource_fields
return [resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()]
File "c:\Users\...\lib\site-packages\import_export\resources.py", line 242, in <listcomp>
return [resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()]
File "c:\Users\...\lib\site-packages\import_export\resources.py", line 882, in export_field
return field.export(obj)
File "c:\Users\...\lib\site-packages\import_export\fields.py", line 125, in export
return self.widget.render(value, obj)
File "c:\Users\...\lib\site-packages\import_export\widgets.py", line 236, in render
value = timezone.localtime(value)
File "c:\Users\...\lib\site-packages\django\utils\timezone.py", line 206, in localtime
raise ValueError("localtime() cannot be applied to a naive datetime")
ValueError: localtime() cannot be applied to a naive datetime
已尝试:
1.从管理员注册中删除了SimpleHistoryAdmin
1.将导入字段变更为仅7/15/2022
1.从导入文件中删除字段
谢谢大家!
1条答案
按热度按时间iezvtpos1#
抱歉,我仔细读了一下:
date_reserved = models.DateTimeField('date reserved', default=datetime.datetime.now)
这就导致了你的错误。你不必设置一个默认值,你可以这样做:
models.DateTimeField(auto_now_add=True)
,它添加当前日期时间(知道),就像您尝试在那里做的那样。这里还是我以前的回答:
这段代码应该可以解决你的问题。你必须解析你的日期时间字符串并将其插入
make_aware
如果您仍然只使用日期,可以执行类似以下操作:
您还可以向模型中添加一个函数,该函数可以自动将初始日期时间转换为感知日期时间check this answer(如果您希望实现此功能的话