2

I have models defined as

class Event(models.Model):
    event_id=models.IntegerField(primary_key=True)
    OS_CHOICE=(('Win 2003','windows 2003'),
        ('Win 2008','Windows 2008'),
        ('Win XP','Windows XP'),
        ('Win VISTA','Win VISTA'),
        ('Win 2007','Windows 2007'),
        )
    windows=models.CharField(max_length=10,choices=OS_CHOICE,default='Win 2003')

    def __unicode__(self):
        return " %s, event_id :%s" \
            % (self.windows, self.event_id)
    class Meta:
        db_table= 'event'
        verbose_name_plural='events'

class Eventgroups(models.Model):
    event=models.ManyToManyField(Event)
    group_name=models.CharField(max_length=100)

    def __unicode__(self):
        return "%s,  %s" \
            % (self.group_name, self.event)
    class Meta:
        db_table= 'eventgroup'
        verbose_name_plural='eventgroups'

class Groups_import(models.Model):
    event_id=models.IntegerField()
    windows=models.CharField(max_length=100)
    group_name=models.CharField(max_length=100)

I want to write a view that imports a csv to database with the above model definition.The user will be asked to browse to where the csv file is located and click on a button to import csv. Anybody with an insight on how to do this please?

madhead
  • 31,729
  • 16
  • 153
  • 201
Joshua
  • 437
  • 2
  • 6
  • 14

1 Answers1

0

You can use:

See how to import csv data into django models

Or you can write your own routines:

# sudo code
file = request.FILES['fileUpload']
data = [row for row in csv.reader(file.read().splitlines())]
for raw in data:
    _, created = Event.objects.get_or_create(
            event_id=row[0],
            windows=row[1]
            )
Community
  • 1
  • 1
fragles
  • 680
  • 6
  • 19
  • Thanks Fragres.Did you consider the M2M field in Eventgroups? and did you mean for row in data: – Joshua Mar 11 '14 at 09:38
  • If you want to use one of these libs, use django-adaptors which is kind of the newest version of django-csv-importer – trez Mar 20 '14 at 06:00