1

I wanted some help with a project I'm working on:

So I have to take a CSV as input from the user and convert the CSV save it as a Table in the Database.

So I was able to take the input from the user and save it in the MEDIA_ROOT. But now I'm unsure how to create a model without knowing the columns and so on. (I know I can get the columns from pandas(in views.py) but how to send that column details to models.py)

I'm new to Django and very much confused with so many files. Please help.

Note: I don't want to save the CSV file I want to convert it into a table in the database.

views.py

import pandas as pd
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView, ListView, CreateView
from django.core.files.storage import FileSystemStorage


def home(request):
    return render(request, 'index.html')


def upload(request):
    if request.method == 'POST':
        upload_file = request.FILES['csvfile']
        fs = FileSystemStorage()
        fs.save(upload_file.name, upload_file)
    dataset = pd.read_csv('media/'+upload_file.name)
    colums = list(dataset.columns)
    
    return render(request, 'upload.html')

models.py

from assignment.settings import MEDIA_ROOT
from django.db import models
from django.db.models.fields import CharField
class CSV(models.Model):
    csvfile = models.FileField(upload_to='CSV')

1 Answer 1

0

The best scenario here is to use a single model called Files and store CSV in a JSON field. You can easily read CSV as a Dict using csv.DictReader and save it in database.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.