user7518095
user7518095

Reputation: 93

User Provided CSV in Django Web Project

I'm using Django to host a web application, and I would like to obtain a CSV file from the user, and process this information (using Python). I am currently using this line of code in the HTML to obtain the CSV file:

<input type="file" accept="text/csv" id="mycsv">

Where in the Django project should I obtain the information from the CSV file, and how would I go about doing this? (I know the question is broad and doesn't give context for my specific project, but I figure that once I know how to access the data in the CSV I can figure the rest out).

Upvotes: 1

Views: 705

Answers (2)

dentemm
dentemm

Reputation: 6379

Step 1: upload the file

# forms.py
from django import forms

class UploadFileForm(forms.Form):
    file  = forms.FileField()

Step 2: parse data and update database

# views.py
import csv

from .models import YourModel

def myview(request):
    if request.method == "POST":    
        form = UploadFileForm(request.POST, request.FILES)

        if form.is_valid():
            reader = csv.reader(form.cleaned_data['file'])

            for row in reader:
                try:
                    some_instance = YourModel.objects.get_or_create(row[...])

            ... 

Upvotes: 1

King Leon
King Leon

Reputation: 1182

Files uploaded by the user will go to the media folder that you have defined in your settings.py file.

You should be able to access user uploaded files in the media directory from your python code with something like this:

file_ = open(os.path.join(settings.MEDIA_ROOT, 'name_of_file'))

More info on MEDIA_ROOT and MEDIA_URL can be found here.

Upvotes: 1

Related Questions