Home > Net >  Is there a way to put JSON data to django models?
Is there a way to put JSON data to django models?

Time:02-28

So what I want to do here is that take a CSV file as input from an HTML form, then convert the CSV to JSON and put the JSON values into a Django model.

I looked on the web, but the answers were not convincing enough, and they were also not what I wanted.

Is there a way to do this? Any help would be appreciated. Thank you in advance!

CodePudding user response:

You can convert CSV data to JSON with csv and json modules as explained in this Stack Overflow discussion

Then, you can store json data in a Django model thank to django-jsonfield. You can have a look at mdegis answer in this Stack Overflow discussion

CodePudding user response:

I am going to give you the logic. I didn't test the code. You may need to clear views.py.

Before we started in the command line:

pip install pandas

in HTML:

<input type="file" accept=".csv" />

in views.py

import pandas as pd

def form_page(request):
    if request.method == 'POST':
        df = pd.read_csv (request.POST.get('csv'))
        df.to_json (turned_json)
        my_obj = CsvModel.objects.create(csv_file=turned_json)
        my_obj.save()
return render(request, 'form.html')

in models.py

class CsvModel(models.Model):
    csv_file = models.FileField()
  • Related