Reputation: 43
I'm new to programming so please bear with me in case I ask silly questions. I'm working on my first project which will gather data from Excel file. I'm trying django-import-export for that purpose but ran into a problem with date containing field. As far as I could understand searching this issue I need to use Date widget, cause it basically reads it as string while importing. But I couldn't find any example where this widget is used so I can see it's syntax. The model I'm working on is shown below. Hope some of you can help me on this. Thanks.
from django.db import models
from import_export.admin import ImportExportModelAdmin
from import_export import widgets
class Employee(models.Model):
name = models.CharField(max_length=200)
badge = models.CharField(max_length=15)
start_date = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=True,widget=widgets.DateWidget(format=None))
end_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True)
status = models.BooleanField(choices=(
(True, 'Active'),
(False, 'Inactive')
), default=True)
job = models.ForeignKey(Matrix, on_delete=models.CASCADE, blank=True, null=True)
location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return str(self.badge)+ str(" - ") + str(self.name)
class Meta:
ordering=('name', 'badge', 'start_date', 'status',)
verbose_name='Employee'
verbose_name_plural='Employees'
Upvotes: 4
Views: 3792
Reputation: 56
First, you have to create a Resource:
from import_export import resources
from import_export.fields import Field
class EmployeeResource(resources.ModelResource):
start_date = Field(attribute='start_date', column_name='<column_name>', widget=DateWidget('<date_format>'))
...
class Meta:
model = Employee
fields = ('start_date',...)
Where <column_name>
is the name of the column and <date_format>
is the format of the incoming date, for example: '%d/%m/%Y'
Then, in your admin.py, you have to link the modeladmin to the resource
class EmployeeAdmin(ImportExportMixin, admin.ModelAdmin):
resource_class = EmployeeResource
Upvotes: 4