ng150716
ng150716

Reputation: 2244

How to Open/Read Uploaded CSV Files in Views

I have a model named source where files are uploaded to, that looks like this:

class Source(models.Model):
    file = models.FileField()
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

and I can call it easily in views like so:

def source_details(request, source_id):
    context_dict = {}

    data_source = Source.objects.get(id=source_id)
    context_dict['data_source'] = data_source

Additionally here are my urls:

url(r'^source/(?P<source_id>[\w\-]+)/$', views.source_details), 

I want to open the csv file that the view is getting so I can loop through each line and display it in a table, any ideas on how I can accomplish this?

Upvotes: 0

Views: 475

Answers (1)

user8060120
user8060120

Reputation:

May be it?

f = data_source.file
f.open(mode='rb') 
source = f.readlines()
f.close()
context_dict['data_source'] = source

Upvotes: 1

Related Questions