Jeremy
Jeremy

Reputation: 821

How to manually associate two models? Data pulled from excel spreadsheet

I'm trying to create an web form where the user enters in a few pieces of information and uploads an excel spreadsheet. During the post (in my views.py) I am trying to open the file and save information within that file into one my models.

The other thing there is two models that are associated together. Anybody have any idea how the views.py might look or if this is possible?

models.py

class service_order(models.Model):
    r_name = models.CharField("Requestor Name", max_length=25)
    r_email = models.CharField("Requestor Email Contact", max_length=25)

class specifications(models.Model):
    service_order = models.ForeignKey(service_order)
    controller_type = models.CharField("Controller", max_length=25)
    hostname = models.CharField("Hostname", max_length=25) 

excel file is pretty simple:

"controller", "hostname", "domain", "ip_address"... etc
"hp server", "sample hostname", "google.com "1.2.3.4"... etc
"hp server", "sample hostname", "google.com "1.2.3.4"... etc
"hp server", "sample hostname", "google.com "1.2.3.4"... etc

I was planning to incorporate xlrd into my django form and views.. here is some preliminary code i was doing to read excel spreadsheets:

import xlrd 

datafile = "sample_survey.xlsx"

def parse_file(datafile):
    workbook = xlrd.open_workbook(datafile)
    sheet = workbook.sheet_by_index(0)

    START_ROW = 35
    END_ROW   = 60

    myList = []

    for row in range(START_ROW,END_ROW):

        values = (sheet.row_values(row, start_colx=1, end_colx=20))

        headers = ["controller", "hostname", "domain", "ip_address", "netmask", "gateway", "dns1", "dns2", "ntp1", "ntp2", 
                   "order_name", "order_phone", "order_email", 
                   "shipping_adress", "shipping_city", "shipping_region", "shipping_region_code", "shipping_country", "shipping_diff"]

        dictionary = dict(zip(headers, values))

        myList.append(dictionary)

    for row in myList:
        print row

data = parse_file(datafile)

Upvotes: 0

Views: 50

Answers (1)

catavaran
catavaran

Reputation: 45575

If each row represents different order then the code will be as simple as:

for row in myList:
    order = service_order.objects.create(r_name=row['order_name'],
                                         r_email=row['order_email'])
    specifications.objects.create(service_order=order,
                                  controller_type=row['controller'],
                                  hostname=row['hostname'])

Also note that in the parse_file() you have to accept the file content instead of file name:

def parse_file(file_contents):
    workbook = xlrd.open_workbook(file_contents=file_contents)
    ...

def my_view(request):
    data_file = request.FILES['data_file']
    parse_file(data_file.read())
    ...

Upvotes: 2

Related Questions