Cohen
Cohen

Reputation: 984

Import a CSV to my Django Models

I need help in order to upload a CSV to my models. I saw that there are some other questions, but they are old, or written in 2.7 and doesn't make no sense.

These are my models.

class Ofac_Sdn(models.Model):
    number = models.IntegerField(blank=True, null=True)
    name = models.CharField(max_length=200, null=True)
    b_i = models.CharField(max_length=250, null=True)
    programe= models.CharField(max_length=250, null=True)
    last_name= models.CharField(max_length=250, null=True)
    more_info = models.CharField(max_length=250, null=True)
    vessel_call_sign = models.CharField(max_length=250, null=True)
    vessel_type= models.CharField(max_length=250, null=True)
    vessel_dwt = models.IntegerField(blank=True, null=True)
    tonnage = models.IntegerField(blank=True, null=True)
    vessel_flag = models.CharField(max_length=250, null=True)
    vessel_owner= models.CharField(max_length=250, null=True)
    dob_aka= models.CharField(max_length=250, null=True)

This is the model of a row from my CSV:

36,AEROCARIBBEAN AIRLINES,-0- ,CUBA,-0- ,-0- ,-0- ,-0- ,-0- ,-0- ,-0- ,-0- 

I have tried until now this example, but i receive an error saying: ModuleNotFoundError: No module named 'settings'

If someone could help, I would owe you a lot as i am stuck here!

Thank you!

import csv, sys, os

project_dir = "/Users/cohen/my-python-project/venv/ofac/ofac_project/ofac_sdn/"

sys.path.append(project_dir)

os.environ['DJANGO_SETTINGS_MODULE']='settings'

import django
django.setup()

from ofac_sdn.models import Ofac_Sdn

data = csv.reader(open('/Users/cohen/my-python-project/venv/ofac/ofac_project/ofac_sdn/sdn.csv')) #,delimiter="|")
#data = csv.reader(open('/Users/cohen/my-python-project/venv/ofac/ofac_project/ofac_sdn/sdn2.csv'), dialect='excel-tab')
for row in data:
    if row[0] !="Number":
        post = Ofac_Sdn()
        post.number = row[0]
        post.name = row[1]
        post.b_i=row[2]
        post.programe=row[3]

        post.more_info=row[4]
        post.vessel_call_sign=row[5]
        post.vessel_type=row[6]
        post.vessel_dwt=row[7]
        post.tonnage=row[8]
        post.vessel_flag=row[9]
        post.vessel_owner=row[10]
        post.dob_aka=row[11]
        post.save()

Upvotes: 1

Views: 994

Answers (2)

user8060120
user8060120

Reputation:

i think you need add you project name:

os.environ['DJANGO_SETTINGS_MODULE']='project_name.settings'
#                                     ^^^^^^^^^^^^

and you can look for django-import-export it can be simple solution

Upvotes: 1

Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13723

The error has nothing to do with CSV importing.

The error is saying there is no such module with the path settings. This means that the you put the wrong path here:

os.environ['DJANGO_SETTINGS_MODULE']='settings'

It should be project_name.settings or the path that fits your project.

Hope it helps.

Upvotes: 2

Related Questions